<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus19.html">Previous Chapter</a>
</ul>
<hr>
<a name="CONCRETE"></a><a name="l363"></a>
<h1>Chapter 20: Concrete examples of C++</h1>
<a name="concrete"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="concrete/intro"></a>In this chapter several concrete examples of <strong>C++</strong> programs, classes and
templates will be presented.  Topics covered by this document such as virtual
functions, <code>static</code> members, etc. are illustrated in this chapter. The
examples roughly follow the organization of earlier chapters.
<p>
First, examples using <code>stream</code> classes are presented, including some
detailed examples illustrating polymorphism.  With the advent of the
<a name="an2786"></a>
ANSI/ISO standard, classes supporting streams based on <a name="an2787"></a>

<em>file descriptors</em> are no longer available, including the <a name="an2788"></a>
Gnu <code>procbuf</code>
extension. These classes were frequently used in older <strong>C++</strong> programs. This
section of the <strong>C++</strong> Annotations develops an alternative: classes extending
<code>streambuf</code>, allowing the use of file descriptors, and classes around the
<a name="an2789"></a>
<code>fork()</code> <a name="an2790"></a>
system call.
<p>
Next, several templates will be developed, both template functions and
full template classes.
<p>
Finally, we'll touch the subjects of <a name="an2791"></a>
scanner and <a name="an2792"></a>
parser generators,
and show how these tools may be used in <strong>C++</strong> programs. These final examples
assume a certain familiarity with the concepts underlying these tools, like
grammars, parse-trees and
        <a name="an2793"></a>

        <a name="an2794"></a>

    parse-tree decoration. Once the input for a program exceeds a certain
level of complexity, it's advantageous to use scanner- and parser-generators
to produce code doing the actual input recognition. One of the
<a href="cplusplus20.html#BisonAndFlex">examples</a> in this chapter describes the usage of these
tools in a <strong>C++</strong> environment.
<p>
<a name="FDSTREAMBUFFER"></a><a name="l364"></a>
<h2>20.1: Using file descriptors with `streambuf' classes</h2>
<p>
<a name="OFDNBUF"></a><a name="l365"></a>
<h3>20.1.1: Classes for output operations</h3>
    <a name="concrete/fdout"></a>    Extensions to the <a name="an2795"></a>
ANSI/ISO standard may be available allowing us to
read from and/or write to <a name="an2796"></a>
<em>file descriptors</em>. However, such extensions are
not standard, and may thus vary or be unavailable across compilers and/or
compiler versions. On the other hand, a file descriptor can be considered a
<a name="an2797"></a>
device. So it seems natural to use the class <a name="an2798"></a>
<code>streambuf</code> as the starting
point for constructing classes interfacing file descriptors.
<p>
In this section we will construct classes which may be used to write to a
device identified by a file descriptor: it may be a file, but it could also be
a <a name="an2799"></a>
pipe or <a name="an2800"></a>
socket. Section <a href="cplusplus20.html#STRBUF">20.1.2</a> discusses reading from devices
given their file descriptors, while section <a href="cplusplus20.html#REDIRECTION">20.3.1</a> reconsiders
redirection, discussed earlier in section <a href="cplusplus05.html#REDIR">5.8.3</a>.
<p>
Basically, deriving a class for <a name="an2801"></a>
output operations is simple. The only
member function that <em>must</em> be overridden is the <a name="an2802"></a>
<code>virtual</code> member <code>int
overflow(int c)</code><a name="an2803"></a>
. This member is responsible for
writing characters to the device once the class's buffer is full. If <code>fd</code> is
a file descriptor to which information may be written, and if we decide
against using a buffer then the member <code>overflow()</code> can simply be:
        <pre>
    class UnbufferedFD: public std::streambuf
    {
        public:
            int overflow(int c);
            ...
    };

    int UnbufferedFD::overflow(int c)
    {
        if (c != EOF)
        {
            if (write(d_fd, &amp;c, 1) != 1)
                return EOF;
        }
        return c;
    }
</pre>
    The argument received by <code>overflow()</code> is either written as a value of
type <code>char</code> to the file descriptor, or <code>EOF</code> is returned.
<p>
This simple function does not use an output buffer. As the use of a buffer
is strongly advised (see also the next section), the construction of a class
using an output buffer will be discussed next in somewhat greater detail.
<p>
When an output buffer is used, the <code>overflow()</code> member will be a bit
more complex, as it is now only called when the buffer is full. Once the
buffer is full, we <em>first</em> have to flush the buffer, for which the (virtual)
function <a name="an2804"></a>
<code>streambuf::sync()</code> is available. Since <code>sync()</code> is a virtual
function, classes derived from <code>std::streambuf</code> may redefine <code>sync()</code> to
flush a buffer <code>std::streambuf</code> itself doesn't know about.
<p>
Overriding <code>sync()</code> and using it in <code>overflow()</code> is not all that has
to be done: eventually we might have less information than fits into the
buffer. So, at the end of the <a name="an2805"></a>
lifetime of our special <code>streambuf</code> object,
its buffer might only be partially full. Therefore, we must make sure that the
buffer is flushed once our object goes <a name="an2806"></a>
out of scope. This is of course very
simple: <code>sync()</code> should be called by the <a name="an2807"></a>
destructor as well.
<p>
Now that we've considered the consequences of using an output buffer,
we're almost ready to construct our derived class. We will add a couple of
additional features, though.
    <ul>
    <li> First, we should allow the user of the class to specify the size of
the output buffer.
    <li> Second, it should be possible to construct an object of our class
before the file descriptor is actually known. Later, in section <a href="cplusplus20.html#FORK">20.3</a>
we'll encounter a situation where this feature will be used.
    </ul>
    In order to save some space, the successful operation of the various
functions was not checked. In `real life' implementations these checks should
of course not be omitted.  Our class <code>ofdnstreambuf</code> has the following
characteristics:
    <ul>
    <li> The class itself is derived from <code>std::streambuf</code>.
    It defines  three data members, keeping track of the size of the buffer,
the file descriptor and the buffer itself. Here is the full class interface
                <pre>
    class ofdnstreambuf: public std::streambuf
    {
        size_t d_bufsize;
        int     d_fd;
        char    *d_buffer;

        public:
            ofdnstreambuf();
            ofdnstreambuf(int fd, size_t bufsize = 1);
            ~ofdnstreambuf();
            void open(int fd, size_t bufsize = 1);
            int sync();
            int overflow(int c);
    };
</pre>
<p>
<li> Its default constructor merely initializes the buffer to 0. Slightly
more interesting is its constructor expecting a filedescriptor and a buffer
size: it simply passes its arguments on to the class's <code>open()</code> member (see
below). Here are the constructors:
                <pre>
    inline ofdnstreambuf::ofdnstreambuf()
    :
        d_bufsize(0),
        d_buffer(0)
    {}

    inline ofdnstreambuf::ofdnstreambuf(int fd, size_t bufsize)
    {
        open(fd, bufsize);
    }
</pre>
<p>
<li> The destructor calls the overridden function <a name="an2808"></a>

<code>sync()</code>, writing any characters stored in the output buffer to the
device. If there's no buffer, the destructor needs to perform no actions:
                <pre>
    inline ofdnstreambuf::~ofdnstreambuf()
    {
        if (d_buffer)
        {
            sync();
            delete[] d_buffer;
        }
    }
</pre>
<p>
Even though the device is not closed in the above implementation this may
not always be what one wants. It is left as an exercise to the reader to
change this class in such a way that the device may optionally remain
open. This approach was followed in, e.g., the
        <a href="http://bobcat.sourceforge.net">Bobcat library</a>.
        <a name="an2809"></a>
<a name="an2810"></a>
 See also section
<a href="cplusplus20.html#IFDNBUF">20.1.2.2</a>.
<p>
<li> The <code>open()</code> member initializes the buffer.  Using
<a name="an2811"></a>
 <code>setp()</code>, the begin and end points of the buffer are
set. This is used by the <code>streambuf</code> base class to initialize
<a name="an2812"></a>
 <code>pbase()</code>, <a name="an2813"></a>
 <code>pptr()</code>, and
<a name="an2814"></a>
 <code>epptr()</code>:
                <pre>
    inline void ofdnstreambuf::open(int fd, size_t bufsize)
    {
        d_fd = fd;
        d_bufsize = bufsize == 0 ? 1 : bufsize;

        d_buffer = new char[d_bufsize];
        setp(d_buffer, d_buffer + d_bufsize);
    }
</pre>
<p>
<li> The member <code>sync()</code> will flush the as yet unflushed contents of the
buffer to the device.  Next, the buffer is reinitialized using
<code>setp()</code>. Note that <code>sync()</code> returns 0 after a successful flush operation:
                <pre>
    inline int ofdnstreambuf::sync()
    {
        if (pptr() &gt; pbase())
        {
            write(d_fd, d_buffer, pptr() - pbase());
            setp(d_buffer, d_buffer + d_bufsize);
        }
        return 0;
    }
</pre>
<p>
<li> Finally, the member <code>overflow()</code> is
            <a name="an2815"></a>

        overridden. Since this member is called from the <code>streambuf</code> base
class when the buffer is full, <code>sync()</code> is called first to flush the filled
up buffer to the device. As this recreates an empty buffer, the character
<code>c</code> which could not be written to the buffer by the <code>streambuf</code> base class
is now entered into the buffer using the member functions <code>pptr()</code> and
<a name="an2816"></a>
 <code>pbump()</code>. Notice that entering a character into the
buffer is realized using available <code>streambuf</code> member functions, rather than
doing it `by hand', which might invalidate <code>streambuf</code>'s internal
bookkeeping:
                <pre>
    inline int ofdnstreambuf::overflow(int c)
    {
        sync();
        if (c != EOF)
        {
            *pptr() = c;
            pbump(1);
        }
        return c;
    }
</pre>
<p>
<li> The member function implementations use low-level functions to
operate on the file descriptors. So apart from <code>streambuf</code> the header file
<a name="an2817"></a>
<code>unistd.h</code> must have been read by the compiler before the implementations of
the member functions can be compiled.
    </ul>
    Depending on the <em>number</em> of arguments, the following program uses the
<code>ofdstreambuf</code> class to copy its standard input to file descriptor
<a name="an2818"></a>
<code>STDOUT_FILENO</code>, which is the <a name="an2819"></a>
symbolic name of the file descriptor used
for the standard output. Here is the program:
        <pre>
    #include &lt;string&gt;
    #include &lt;iostream&gt;
    #include &lt;istream&gt;
    #include "fdout.h"
    using namespace std;

    int main(int argc)
    {
        ofdnstreambuf   fds(STDOUT_FILENO, 500);
        ostream         os(&amp;fds);

        switch (argc)
        {
            case 1:
                os &lt;&lt; "COPYING cin LINE BY LINE\n";
                for (string  s; getline(cin, s); )
                    os &lt;&lt; s &lt;&lt; endl;
            break;

            case 2:
                os &lt;&lt; "COPYING cin BY EXTRACTING TO os.rdbuf()\n";

                cin &gt;&gt; os.rdbuf();      // Alternatively, use:  cin &gt;&gt; &amp;fds;
            break;

            case 3:
                os &lt;&lt; "COPYING cin BY INSERTING cin.rdbuf() into os\n";
                os &lt;&lt; cin.rdbuf();
            break;
        }
    }
</pre>
<p>
<a name="STRBUF"></a><a name="l366"></a>
<h3>20.1.2: Classes for input operations</h3>
    <a name="concrete/fdinput"></a>    When classes to be used for input operation are derived from
<code>std::</code><a name="an2820"></a>
<code>streambuf</code>, they should be provided with an input buffer of at
least one character. The one-character input buffer allows for the use of the
member functions <a name="an2821"></a>
<code>istream::putback()</code> or <a name="an2822"></a>
<code>istream::ungetc()</code>.  Stream
classes (like <a name="an2823"></a>
<code>istream</code>) normally allow us to unget at least one character
using their member functions <code>putback()</code> or <code>ungetc()</code>. This is important,
as these stream classes usually interface to <a name="an2824"></a>
<code>streambuf</code> objects. Although
it is strictly speaking not necessary to implement a buffer in classes derived
from <code>streambuf</code>, using buffers in these cases is strongly advised: the
implementation is very simple and straightforward, and the applicability of
such classes will be greatly improved. Therefore, in all our classes
        <a name="an2825"></a>

    derived from the class <code>streambuf</code> <em>at least</em> a <a name="an2826"></a>
buffer of one
character will be defined.
<p>
<a name="IFDBUF"></a><a name="l367"></a>
<strong>20.1.2.1: Using a one-character buffer</strong>
        <a name="concrete/fdinbuf"></a>    When deriving a class (e.g., <a name="an2827"></a>
<code>ifdstreambuf</code>) from <code>streambuf</code> using a
buffer of one character, at least its member <code>streambuf::underflow()</code> should
be overridden, as this is the member to which all requests for input are
eventually directed. Since a buffer is also needed, the member
<a name="an2828"></a>
<code>streambuf::setg()</code> is used to inform the <code>streambuf</code> base class of the
size of the input buffer, so that it is able to set up its input buffer
pointers correctly. This will ensure that
    <a name="an2829"></a>
 <code>eback()</code>,
    <a name="an2830"></a>
 <code>gptr()</code>, and
    <a name="an2831"></a>
 <code>egptr()</code> return correct values.
<p>
The required class shows the following characteristics:
    <ul>
    <li> Like the class designed for output operations, this class is derived
from <code>std::</code><a name="an2832"></a>
<code>streambuf</code> as well.
    The class defines two data members, one of them a fixed-sized one
character buffer. The data members are defined as <a name="an2833"></a>
<code>protected</code> data members
so that derived classes (e.g., see section <a href="cplusplus20.html#IFDSEEK">20.1.2.3</a>) can access them. Here
is the full class interface:
                <pre>
    class ifdstreambuf: public std::streambuf
    {
        protected:
            int     d_fd;
            char    d_buffer[1];
        public:
            ifdstreambuf(int fd);
            int underflow();
    };
</pre>
<p>
<li> The constructor initializes the buffer. However, this initialization
is done so that <a name="an2834"></a>
<code>gptr()</code> will be equal to <a name="an2835"></a>
<code>egptr()</code>. Since this implies
that the buffer is empty, <code>underflow()</code> will immediately be called to refill
the buffer:
                <pre>
    inline ifdstreambuf::ifdstreambuf(int fd)
    :
        d_fd(fd)
    {
        setg(d_buffer, d_buffer + 1, d_buffer + 1);
    }
</pre>
<p>
<li> Finally <code>underflow()</code> is overridden. It will first ensure that the
buffer is really empty. If not, then the next character in the buffer is
returned. If the buffer is really empty, it is refilled by reading from the
file descriptor. If this fails (for whatever reason), <code>EOF</code> is
returned. More sophisticated implementations could react more intelligently
here, of course. If the buffer could be refilled, <a name="an2836"></a>
<code>setg()</code> is called to set
up <code>streambuf</code>'s buffer pointers correctly.
    <li> The implementations of the member functions use low-level functions
to operate the file descriptors, so apart from <code>streambuf</code> the header file
<a name="an2837"></a>
<code>unistd.h</code> must have been read by the compiler before the implementations of
the member functions can be compiled.
    </ul>
    This completes the construction of the <code>ifdstreambuf</code> class. It is used
in the following program:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;istream&gt;
    #include &lt;unistd.h&gt;
    #include "ifdbuf.h"
    using namespace std;

    int main(int argc)
    {
        ifdstreambuf fds(STDIN_FILENO);
        istream      is(&amp;fds);

        cout &lt;&lt; is.rdbuf();
    }
</pre>
<p>
<a name="IFDNBUF"></a><a name="l368"></a>
<strong>20.1.2.2: Using an n-character buffer</strong>
        <a name="concrete/fdninbuf"></a>    How complex would things get if we would decide to use a buffer of
substantial size? Not that complex. The following class allows us to specify
the size of a buffer, but apart from that it is basically the same class as
<code>ifdstreambuf</code> developed in the previous section. To make things a bit more
interesting, in the class <a name="an2838"></a>
<code>ifdnstreambuf</code> developed here, the member
<a name="an2839"></a>
<code>streambuf::xsgetn()</code> is also overridden, to optimize reading of series of
characters. Furthermore, a default constructor is provided which can be used
in combination with the <code>open()</code> member to construct an <code>istream</code> object
before the file descriptor becomes available. Then, once the descriptor
becomes available, the <code>open()</code> member can be used to initiate the object's
buffer. Later, in section <a href="cplusplus20.html#FORK">20.3</a>, we'll encounter such a situation.
<p>
To save some space, the success of various calls was not checked. In `real
life' implementations, these checks should, of course, not be omitted. The
class <code>ifdnstreambuf</code> has the following characteristics:
    <ul>
    <li> Once again, it is derived from <code>std::</code><a name="an2840"></a>
<code>streambuf</code>:
        Like the class <code>ifdstreambuf</code> (section <a href="cplusplus20.html#IFDBUF">20.1.2.1</a>), its data
members are protected. Since the buffer's size is configurable, this size is
kept in a dedicated data member, <code>d_bufsize</code>:
                    <pre>
    class ifdnstreambuf: public std::streambuf
    {
        protected:
            int         d_fd;
            size_t    d_bufsize;
            char*       d_buffer;
        public:
            ifdnstreambuf();
            ifdnstreambuf(int fd, size_t bufsize = 1);
            ~ifdnstreambuf();
            void open(int fd, size_t bufsize = 1);
            int underflow();
            std::streamsize xsgetn(char *dest, std::streamsize n);
    };
</pre>
<p>
<li> The default constructor does not allocate a buffer, and can be used
to construct an object before the file descriptor becomes known. A second
constructor simply passes its arguments to <code>open()</code> which will then
initialize the object so that it can actually be used:
                    <pre>
    inline ifdnstreambuf::ifdnstreambuf()
    :
        d_bufsize(0),
        d_buffer(0)
    {}
    inline ifdnstreambuf::ifdnstreambuf(int fd, size_t bufsize)
    {
        open(fd, bufsize);
    }
</pre>
<p>
<li> If the object has been initialized by <code>open()</code>, its destructor will
both delete the object's buffer and use the file descriptor to close the
device:
                    <pre>
    ifdnstreambuf::~ifdnstreambuf()
    {
        if (d_bufsize)
        {
            close(d_fd);
            delete[] d_buffer;
        }
    }
</pre>
<p>
Even though the device is closed in the above implementation this may not
always be what one wants. In cases where the open file descriptor is already
available the intention may be to use that descriptor repeatedly, each time
using a newly constructed <code>ifdnstreambuf</code> object. It is left as an exercise
to the reader to change this class in such a way that the device may
optionally be closed. This approach was followed in, e.g., the
        <a href="http://bobcat.sourceforge.net">Bobcat library</a>.
        <a name="an2841"></a>
<a name="an2842"></a>

    <li> The <code>open()</code> member simply allocates the object's buffer. It is
assumed that the calling program has already opened the device. Once the
buffer has been allocated, the base class member <code>setg()</code> is used to
ensure that
    <a name="an2843"></a>
 <code>eback()</code>,
    <a name="an2844"></a>
 <code>gptr()</code>, and
    <a name="an2845"></a>
 <code>egptr()</code> return correct values:
                    <pre>
    void ifdnstreambuf::open(int fd, size_t bufsize)
    {
        d_fd = fd;
        d_bufsize = bufsize;
        d_buffer = new char[d_bufsize];
        setg(d_buffer, d_buffer + d_bufsize, d_buffer + d_bufsize);
    }
</pre>
<p>
<li> The overridden member <code>underflow()</code> is implemented almost
identically to <code>ifdstreambuf</code>'s (section <a href="cplusplus20.html#IFDBUF">20.1.2.1</a>) member. The only
difference is that the current class supports a buffer of larger
sizes. Therefore, more characters (up to <code>d_bufsize</code>) may be read from the
device at once:
                    <pre>
    int ifdnstreambuf::underflow()
    {
        if (gptr() &lt; egptr())
            return *gptr();

        int nread = read(d_fd, d_buffer, d_bufsize);

        if (nread &lt;= 0)
            return EOF;

        setg(d_buffer, d_buffer, d_buffer + nread);
        return *gptr();
    }
</pre>
<p>
<li> Finally <code>xsgetn()</code> is overridden. In a loop, <code>n</code> is reduced until
0, at which point the function terminates. Alternatively, the member returns
if <code>underflow()</code> fails to obtain more characters. This member optimizes the
reading of series of characters: instead of calling <a name="an2846"></a>
<code>streambuf::sbumpc()</code>
<code>n</code> times, a block of <code>avail</code> characters is copied to the destination,
using <a name="an2847"></a>
<code>streambuf::gpumb()</code> to consume <code>avail</code> characters from the buffer
using one function call:
                    <pre>
    std::streamsize ifdnstreambuf::xsgetn(char *dest, std::streamsize n)
    {
        int nread = 0;

        while (n)
        {
            if (!in_avail())
            {
                if (underflow() == EOF)
                    break;
            }

            int avail = in_avail();

            if (avail &gt; n)
                avail = n;

            memcpy(dest + nread, gptr(), avail);
            gbump(avail);

            nread += avail;
            n -= avail;
        }

        return nread;
    }
</pre>
<p>
<li> The implementations of the member functions use low-level functions
to operate the file descriptors. So apart from <code>streambuf</code> the header file
<a name="an2848"></a>
<code>unistd.h</code> must have been read by the compiler before the implementations of
the member functions can be compiled.
    </ul>
    The member function <code>xsgetn()</code> is called by <a name="an2849"></a>
<code>streambuf::sgetn()</code>,
which is a <code>streambuf</code> member. The following example illustrates the use of
this member function with a <code>ifdnstreambuf</code> object:
        <pre>
    #include &lt;unistd.h&gt;
    #include &lt;iostream&gt;
    #include &lt;istream&gt;
    #include "ifdnbuf.h"
    using namespace std;

    int main(int argc)
    {
                                    // internally: 30 char buffer
        ifdnstreambuf fds(STDIN_FILENO, 30);

        char buf[80];               // main() reads blocks of 80
                                    // chars
        while (true)
        {
            size_t n = fds.sgetn(buf, 80);
            if (n == 0)
                break;
            cout.write(buf, n);
        }
    }
</pre>
<p>
<a name="IFDSEEK"></a><a name="l369"></a>
<strong>20.1.2.3: Seeking positions in `streambuf' objects</strong>
        <a name="concrete/fdinseek"></a>    When devices support <em>seek operations</em>, classes derived from
<a name="an2850"></a>
<code>streambuf</code> should override the members <a name="an2851"></a>
<code>streambuf::seekoff()</code> and
<a name="an2852"></a>
<code>streambuf::seekpos()</code>. The class <a name="an2853"></a>
<code>ifdseek</code>, developed in this section,
can be used to read information from devices supporting such seek
operations. The class <code>ifdseek</code> was derived from <code>ifdstreambuf</code>, so it
uses a character buffer of just one character. The facilities to perform seek
operations, which are added to our new class <code>ifdseek</code>, will make sure that
the input buffer is reset when a seek operation is requested. The class could
also be derived from the class <code>ifdnstreambuf</code>; in which case, the arguments
to reset the input buffer must be adapted in such a way that its second and
third parameters point beyond the available input buffer. Let's have a look at
the characteristics of <code>ifdseek</code>:
    <ul>
    <li> As mentioned, <code>ifdseek</code> is derived from <code>ifdstreambuf</code>. Like the
latter class, <code>ifdseek</code>'s member functions use facilities declared in
<code>unistd.h</code>. So, the compiler must have seen <code>unistd.h</code> before it can
compile the class's members functions.  To reduce the amount of typing when
specifying types and constants from <code>std::streambuf</code> and <code>std::ios</code>,
several <a name="an2854"></a>
<code>typedef</code>s are defined at the class's very top.  These typedefs
refer to types that are defined in the header file <a name="an2855"></a>
<code>ios</code>, which must
therefore be included as well before the compiler reads <code>ifdseek</code>'s class
definition. Here is the class's interface:
                <pre>
    class ifdseek: public ifdstreambuf
    {
        typedef std::streambuf::pos_type        pos_type;
        typedef std::streambuf::off_type        off_type;
        typedef std::ios::seekdir               seekdir;
        typedef std::ios::openmode              openmode;

        public:
            ifdseek(int fd);
            pos_type seekoff(off_type offset, seekdir dir, openmode);
            pos_type seekpos(pos_type offset, openmode mode);
    };
</pre>
<p>
<li> The class is given a rather basic implementation. The only required
constructor expects the device's <a name="an2856"></a>
file descriptor. It has no special tasks
to perform and only needs to call its <a name="an2857"></a>
base class constructor:
                <pre>
    inline ifdseek::ifdseek(int fd)
    :
        ifdstreambuf(fd)
    {}
</pre>
<p>
<li> The member <code>seek_off()</code> is responsible for performing the actual
seek operations. It calls <a name="an2858"></a>
<code>lseek()</code> to seek a new position in a device whose
file descriptor is known. If seeking succeeds, <code>setg()</code> is called to define
an already empty buffer, so that the base class's <code>underflow()</code> member
will refill the buffer at the next input request.
                <pre>
    ifdseek::pos_type ifdseek::seekoff(off_type off, seekdir dir, openmode)
    {
        pos_type pos =
            lseek
            (
                d_fd, off,
                (dir ==  std::ios::beg) ? SEEK_SET :
                (dir ==  std::ios::cur) ? SEEK_CUR :
                                          SEEK_END
            );

        if (pos &lt; 0)
            return -1;

        setg(d_buffer, d_buffer + 1, d_buffer + 1);
        return pos;
    }
</pre>
<p>
<li> Finally,  the companion function <code>seekpos</code> is overridden as well:
it is actually defined as a call to <code>seekoff()</code>:
                <pre>
    inline ifdseek::pos_type ifdseek::seekpos(pos_type off, openmode mode)
    {
        return seekoff(off, std::ios::beg, mode);
    }
</pre>
<p>
</ul>
    An example of a program using the class <code>ifdseek</code> is the following. If
this program is given its own source file using input <a name="an2859"></a>
redirection then
seeking is supported, and with the exception of the first line, every other
line is shown twice:
        <pre>
    #include "fdinseek.h"
    #include &lt;string&gt;
    #include &lt;iostream&gt;
    #include &lt;istream&gt;
    #include &lt;iomanip&gt;
    using namespace std;

    int main(int argc)
    {
        ifdseek fds(0);
        istream is(&amp;fds);
        string  s;

        while (true)
        {
            if (!getline(is, s))
                break;

            streampos pos = is.tellg();

            cout &lt;&lt; setw(5) &lt;&lt; pos &lt;&lt; ": `" &lt;&lt; s &lt;&lt; "'\n";

            if (!getline(is, s))
                break;

            streampos pos2 = is.tellg();

            cout &lt;&lt; setw(5) &lt;&lt; pos2 &lt;&lt; ": `" &lt;&lt; s &lt;&lt; "'\n";

            if (!is.seekg(pos))
            {
                cout &lt;&lt; "Seek failed\n";
                break;
            }
        }
    }
</pre>
<p>
<a name="l370"></a>
<strong>20.1.2.4: Multiple `unget()' calls in `streambuf' objects</strong>
        <a name="concrete/fdunget"></a>    As mentioned before, <a name="an2860"></a>
<code>streambuf</code> classes and classes derived from
<code>streambuf</code> should support <em>at least</em> ungetting the last read
character. Special care must be taken when <em>series</em> of <code>unget()</code> calls
must be supported. In this section the construction of a class supporting a
configurable number of <a name="an2861"></a>
<code>istream::unget()</code> or <a name="an2862"></a>
<code>istream::putback()</code> calls is
discussed.
<p>
Support for multiple (say `<code>n</code>') <code>unget()</code> calls is realized by
reserving an initial section of the input buffer, which is gradually filled up
to contain the last <code>n</code> characters read. The class was implemented as
follows:
    <ul>
    <li> Once again, the class is derived from <code>std::</code><a name="an2863"></a>
<code>streambuf</code>. It
defines several data members, allowing the class to perform the bookkeeping
required to maintain an unget-buffer of a configurable size:
                <pre>
    class fdunget: public std::streambuf
    {
        int         d_fd;
        size_t    d_bufsize;
        size_t    d_reserved;
        char*       d_buffer;
        char*       d_base;

        public:
            fdunget(int fd, size_t bufsz, size_t unget);
            ~fdunget();
            int underflow();
    };
</pre>
<p>
<li> The class's constructor expects a <a name="an2864"></a>
file descriptor, a buffer size
and the number of characters that can be ungot or pushed back as its
arguments. This number  determines the size of a <em>reserved</em> area,
defined as the first <code>d_reserved</code> bytes of the class's input buffer.
        <ul>
        <li> The input buffer will always be  at least one byte larger than
<code>d_reserved</code>. So, a certain number of bytes may be read. Then, once
<code>reserved</code> bytes have been read at least <code>reserved</code> bytes can be ungot.
        <li> Next, the starting point for reading operations is configured: it
is called <code>d_base</code>, pointing to a location <code>reserved</code> bytes from the start
of <code>d_buffer</code>. This will always be the point where the buffer refills start.
        <li> Now that the buffer has been constructed, we're ready to define
<code>streambuf</code>'s buffer pointers using <code>setg()</code>. As no characters have been
read yet, all pointers are set to point to <code>d_base</code>. If <code>unget()</code> is
called at this point, no characters are available, so <code>unget()</code> will
(correctly) fail.
        <li> Eventually, the refill buffer's size is determined as the
number of allocated bytes minus the size of the reserved area.
        </ul>
        Here is the class's constructor:
                    <pre>
    fdunget::fdunget(int fd, size_t bufsz, size_t unget)
    :
        d_fd(fd),
        d_reserved(unget)
    {
        size_t allocate =
                bufsz &gt; d_reserved ?
                    bufsz
                :
                    d_reserved + 1;

        d_buffer = new char[allocate];

        d_base = d_buffer + d_reserved;
        setg(d_base, d_base, d_base);

        d_bufsize = allocate - d_reserved;
    }
</pre>
<p>
<li> The class's destructor simply returns the memory allocated for the
buffer to the common pool:
                    <pre>
    inline fdunget::~fdunget()
    {
        delete[] d_buffer;
    }
</pre>
<p>
<li> Finally,  <code>underflow()</code> is overridden.
        <ul>
        <li> Firstly, the standard check to determine whether the buffer is
really empty is applied.
        <li> If empty, it determines the number of characters that could
potentially be ungot. At this point, the input buffer is exhausted. So this
value may be any value between 0 (the initial state) or the input buffer's
size (when the reserved area has been filled up completely, and all current
characters in the remaining section of the buffer have also been read).
        <li> Next the number of bytes to move into the reserved area is
computed. This number is at most <code>d_reserved</code>, but it is equal to the actual
number of characters that can be ungot if this value is smaller.
        <li> Now that the number of characters to move into the reserved area
is known, this number of characters is moved from the input buffer's end to
the area immediately before <code>d_base</code>.
        <li> Then the buffer is refilled. This all is standard, but notice
that reading starts from <code>d_base</code> and not from <code>d_buffer</code>.
        <li> Finally, <code>streambuf</code>'s read buffer pointers are set up.
                <a name="an2865"></a>

            <code>Eback()</code> is set to <code>move</code> locations before <code>d_base</code>, thus
defining the guaranteed unget-area,
                <a name="an2866"></a>

            <code>gptr()</code> is set to <code>d_base</code>, since that's the location of the
first read character after a refill, and
                <a name="an2867"></a>

            <code>egptr()</code> is set just beyond the location of the last character
read into the buffer.
        </ul>
        Here is <code>underflow()</code>'s implementation:
                    <pre>
    int fdunget::underflow()
    {
        if (gptr() &lt; egptr())
            return *gptr();

        size_t ungetsize = gptr() - eback();
        size_t move = std::min(ungetsize, d_reserved);

        memcpy(d_base - move, egptr() - move, move);

        int nread = read(d_fd, d_base, d_bufsize);
        if (nread &lt;= 0)       // none read -&gt; return EOF
            return EOF;

        setg(d_base - move, d_base, d_base + nread);

        return *gptr();
    }
</pre>
<p>
</ul>
    The following program illustrates the <code>class fdunget</code>. It reads at most
10 characters from the standard input, stopping at <code>EOF</code>. A guaranteed
unget-buffer of 2 characters is defined in a buffer holding 3 characters. Just
before reading a character, the program tries to unget at most 6
characters. This is, of course, not possible; but the program will nicely
unget as many characters as possible, considering the actual number of
characters read:
        <pre>
    #include "fdunget.h"
    #include &lt;string&gt;
    #include &lt;iostream&gt;
    #include &lt;istream&gt;
    using namespace std;

    int main(int argc)
    {
        fdunget fds(0, 3, 2);
        istream is(&amp;fds);
        char    c;

        for (int idx = 0; idx &lt; 10; ++idx)
        {
            cout &lt;&lt; "after reading " &lt;&lt; idx &lt;&lt; " characters:\n";
            for (int ug = 0; ug &lt;= 6; ++ug)
            {
                if (!is.unget())
                {
                    cout
                    &lt;&lt; "\tunget failed at attempt " &lt;&lt; (ug + 1) &lt;&lt; "\n"
                    &lt;&lt; "\trereading: '";

                    is.clear();
                    while (ug--)
                    {
                        is.get(c);
                        cout &lt;&lt; c;
                    }
                    cout &lt;&lt; "'\n";
                    break;
                }
            }

            if (!is.get(c))
            {
                cout &lt;&lt; " reached\n";
                break;
            }
            cout &lt;&lt; "Next character: " &lt;&lt; c &lt;&lt; endl;
        }
    }
    /*
        Generated output after 'echo abcde | program':

        after reading 0 characters:
                unget failed at attempt 1
                rereading: ''
        Next character: a
        after reading 1 characters:
                unget failed at attempt 2
                rereading: 'a'
        Next character: b
        after reading 2 characters:
                unget failed at attempt 3
                rereading: 'ab'
        Next character: c
        after reading 3 characters:
                unget failed at attempt 4
                rereading: 'abc'
        Next character: d
        after reading 4 characters:
                unget failed at attempt 4
                rereading: 'bcd'
        Next character: e
        after reading 5 characters:
                unget failed at attempt 4
                rereading: 'cde'
        Next character:

        after reading 6 characters:
                unget failed at attempt 4
                rereading: 'de
        '
         reached
    */
</pre>
<p>
<a name="l371"></a>
<h2>20.2: Fixed-sized field extraction from istream objects</h2>
    <a name="concrete/fistream"></a>Usually when extracting information from <code>istream</code> objects <code>operator</code>>><code>()</code>, the
standard extraction operator, is perfectly suited for the task as in most
cases the extracted fields are white-space or otherwise clearly separated from
each other. But this does not hold true in all situations. For example, when a
web-form is posted to some processing script or program, the receiving program
may receive the form field's values as <a name="an2868"></a>
<em>url-encode</em><em>d</em> characters: letters
and digits are sent unaltered, blanks are sent as <code>+</code> characters, and all
other characters start with <code>%</code> followed by the character's
    <a name="an2869"></a>
ascii-value represented by its two digit hexadecimal value.
<p>
When decoding url-encoded information, a simple hexadecimal extraction
won't work, since that will extract as many hexadecimal characters as
available, instead of just two. Since the letters <code>a-f</code> and <code>0-9</code> are
legal hexadecimal characters, a text like <code>My name is `Ed'</code>, url-encoded as
        <pre>
        My+name+is+%60Ed%27
</pre>
    will result in the extraction of the hexadecimal values <code>60ed</code> and
<code>27</code>, instead of <code>60</code> and <code>27</code>. The name <code>Ed</code> will disappear from
view, which is clearly not what we want.
<p>
In this case, having seen the <code>%</code>, we could extract 2 characters, put
them in an <a name="an2870"></a>
<code>istringstream</code> object, and extract the hexadecimal value from
the <code>istringstream</code> object. A bit cumbersome, but doable. Other approaches,
however, are possible as well.
<p>
The following class <a name="an2871"></a>
<code>fistream</code> for <em>fixed-sized field istream</em> defines
an <code>istream</code> class supporting both fixed-sized field extractions and
blank-delimited extractions (as well as unformatted <code>read()</code> calls). The
class may be initialized as a <a name="an2872"></a>
<em>wrapper</em> around an existing <code>istream</code>, or
it can be initialized using the name of an existing file. The class is derived
from <code>istream</code>, allowing all extractions and operations supported by
<code>istream</code>s in general. The class will need the following data members:
    <ul>
    <li><code>d_filebuf</code>: a filebuffer used when <code>fistream</code> reads its information
        from a named (existing) file. Since the filebuffer is only needed in
        that case, and since it must be allocated dynamically, it is defined
        as an <code>auto_ptr&lt;filebuf&gt;</code> object.
    <li><code>d_streambuf</code>: a pointer to <code>fistream</code>'s <code>streambuf</code>. It will point
        to <code>filebuf</code> when <code>fistream</code> opens a file by name. When an
        existing <code>istream</code> is used to construct an <code>fistream</code>, it will
        point to the existing <code>istream</code>'s <code>streambuf</code>.
    <li><code>d_iss</code>: an <code>istringstream</code> object which is used for the fixed field
        extractions.
    <li><code>d_width</code>: an <code>size_t</code> indicating the width of the field to
        extract. If 0 no fixed field extractions will be used, but
        information will be extracted from the <code>istream</code> base class object
        using standard extractions.
    </ul>
    Here is the initial section of <code>fistream</code>'s class interface:
                <pre>
    class fistream: public std::istream
    {
        std::auto_ptr&lt;std::filebuf&gt; d_filebuf;
        std::streambuf *d_streambuf;
        std::istringstream d_iss;
        size_t d_width;
</pre>
<p>
As mentioned, <code>fistream</code> objects can be constructed from either a
filename or an existing <code>istream</code> object. Thus, the class interface shows
two constructors:
                <pre>
            fistream(std::istream &amp;stream);
            fistream(char const *name,
                std::ios::openmode mode = std::ios::in);
</pre>
<p>
When an <code>fistream</code> object is constructed using an existing <code>istream</code>
object, the <code>fistream</code>'s <code>istream</code> part will simply use the <code>stream</code>'s
<code>streambuf</code> object:
                <pre>
fistream::fistream(istream &amp;stream)
:
    istream(stream.rdbuf()),
    d_streambuf(rdbuf()),
    d_width(0)
{}
</pre>
<p>
When an <code>fstream</code> object is constructed using a filename, the
<code>istream</code> base initializer is given a new <code>filebuf</code> object to be used as
its <code>streambuf</code>. Since the class's data members are not initialized before
the class's base class has been constructed, <code>d_filebuf</code> can only be
initialized thereafter. By then, the <code>filebuf</code> is only available as
<code>rdbuf()</code>, which returns a <code>streambuf</code>. However, as it is actually a
<code>filebuf</code>, a <code>reinterpret_cast</code> is used to cast the <code>streambuf</code> pointer
returned by <code>rdbuf()</code> to <code>a filebuf *</code>, so <code>d_filebuf</code> can be
initialized:
                <pre>
fistream::fistream(char const *name, ios::openmode mode)
:
    istream(new filebuf()),
    d_filebuf(reinterpret_cast&lt;filebuf *&gt;(rdbuf())),
    d_streambuf(d_filebuf.get()),
    d_width(0)
{
    d_filebuf-&gt;open(name, mode);
}
</pre>
<p>
There is only one additional public member: <code>setField(field const
&amp;)</code>. This member is used to define the size of the next field to extract. Its
parameter is a reference to a <code>field</code> class, a <a name="an2873"></a>
<em>manipulator class</em>
defining the width of the next field.
<p>
Since a <code>field &amp;</code> is mentioned in <code>fistream</code>'s interface, <code>field</code>
must be declared before <code>fistream</code>'s interface starts. The class <code>field</code>
itself is simple: it declares <code>fistream</code> as its friend, and it has two data
members: <code>d_width</code> specifies the width of the next field, <code>d_newWidth</code> is
set to <code>true</code> if <code>d_width</code>'s value should actually be used. If
<code>d_newWidth</code> is false, <code>fistream</code> will return to its standard extraction
mode. The class <code>field</code> furthermore has two constructors: a default
constructor, setting <code>d_newWidth</code> to <code>false</code> and a second constructor
expecting the width of the next field to extract as its value. Here is the
class <code>field</code>:
                <pre>
    class field
    {
        friend class fistream;
        size_t d_width;
        bool     d_newWidth;

        public:
            field(size_t width);
            field();
    };

    inline field::field(size_t width)
    :
        d_width(width),
        d_newWidth(true)
    {}

    inline field::field()
    :
        d_newWidth(false)
    {}
</pre>
<p>
Since <code>field</code> declares <code>fistream</code> as its friend, <code>setField</code> may
inspect <code>field</code>'s members directly.
<p>
Time to return to <code>setField()</code>. This function expects a reference to a
<code>field</code> object, initialized in either of three different ways:
    <ul>
    <li><code>field()</code>: When <code>setField()</code>'s argument is a <code>field</code> object
        constructed by its default constructor the next extraction will use
        the same fieldwidth as the previous extraction.
    <li><code>field(0)</code>: When this <code>field</code> object is used as <code>setField()</code>'s
        argument, fixed-sized field extraction stops, and the <code>fistream</code>
        will act like any standard <code>istream</code> object.
    <li><code>field(x)</code>: When the <code>field</code> object itself is initialized by a
        non-zero size_t value <code>x</code>, then the next field width will be <code>x</code>
        characters wide. The preparation of such a field is left to
        <code>setBuffer()</code>, <code>fistream</code>'s only private member.
    </ul>
    Here is <code>setField()</code>'s implementation:
                <pre>
std::istream &amp;fistream::setField(field const &amp;params)
{
    if (params.d_newWidth)                  // new field size requested
        d_width = params.d_width;           // set new width

    if (!d_width)                           // no width?
        rdbuf(d_streambuf);                 // return to the old buffer
    else
        setBuffer();                        // define the extraction buffer

    return *this;
}
</pre>
<p>
The private member <code>setBuffer()</code> defines a buffer of <code>d_width + 1</code>
characters, and uses <code>read()</code> to fill the buffer with <code>d_width</code>
characters. The buffer is terminated by an <code>ASCII-Z</code> character. This buffer
is then used to initialize the <code>d_str</code> member. Finally, <code>fistream</code>'s
<code>rdbuf()</code> member is used to extract the <code>d_str</code>'s data via the
<code>fistream</code> object itself:
                <pre>
void fistream::setBuffer()
{
    char *buffer = new char[d_width + 1];

    rdbuf(d_streambuf);                     // use istream's buffer to
    buffer[read(buffer, d_width).gcount()] = 0; // read d_width chars,
                                                // terminated by ascii-Z
    d_iss.str(buffer);
    delete buffer;

    rdbuf(d_iss.rdbuf());                   // switch buffers
}
</pre>
<p>
Although <code>setField()</code> could be used to configure <code>fistream</code> to use or
not to use fixed-sized field extraction, using <a name="an2874"></a>
manipulators is probably
preferable. To allow <code>field</code> objects to be used as manipulators, an
overloaded extraction operator was defined, accepting an <code>istream &amp;</code> and a
<code>field const &amp;</code> object. Using this extraction operator, statements like
        <pre>
fis &gt;&gt; field(2) &gt;&gt; x &gt;&gt; field(0);
</pre>
    are possible (assuming <code>fis</code> is a <code>fistream</code> object). Here is the
overloaded <code>operator</code>>><code>()</code>, as well as its declaration:
                <pre>
istream &amp;std::operator&gt;&gt;(istream &amp;str, field const &amp;params)
{
    return reinterpret_cast&lt;fistream *&gt;(&amp;str)-&gt;setField(params);
}
</pre>
<p>
Declaration:
                <pre>
namespace std
{
    istream &amp;operator&gt;&gt;(istream &amp;str, FBB::field const &amp;params);
}
</pre>
<p>
Finally, an example. The following program uses a <code>fistream</code> object to
url-decode url-encoded information appearing at its standard input:
                <pre>
    int main()
    {
        fistream fis(cin);

        fis &gt;&gt; hex;
        while (true)
        {
            size_t x;
            switch (x = fis.get())
            {
                case '\n':
                    cout &lt;&lt; endl;
                break;
                case '+':
                    cout &lt;&lt; ' ';
                break;
                case '%':
                    fis &gt;&gt; field(2) &gt;&gt; x &gt;&gt; field(0);
                // FALLING THROUGH
                default:
                    cout &lt;&lt; static_cast&lt;char&gt;(x);
                break;
                case EOF:
                return 0;
            }
        }
    }
    /*
        Generated output after:
            echo My+name+is+%60Ed%27 | a.out

        My name is `Ed'
    */
</pre>
<p>
<a name="FORK"></a><a name="l372"></a>
<h2>20.3: The `fork()' system call</h2>
<a name="concrete/fork"></a>From  the <strong>C</strong> programming language, the <a name="an2875"></a>
<code>fork()</code> <a name="an2876"></a>
system call is well
known. When a program needs to start a new process, <a name="an2877"></a>
<code>system()</code> can be used,
but this requires the program to wait for the <a name="an2878"></a>
<em>child process</em> to
terminate. The more general way to spawn subprocesses is to call <code>fork()</code>.
<p>
In this section we will see how <strong>C++</strong> can be used to wrap classes around a
complex system call like <code>fork()</code>. Much of what follows in this section
directly applies to the <a name="an2879"></a>
Unix <a name="an2880"></a>
operating system, and the discussion will
therefore focus on that operating system. However, other systems usually
provide comparable facilities. The following discussion is based heavily on
the notion of <a name="an2881"></a>
<em>design patterns</em>, as published by <em>Gamma et al.</em> (1995)
    <a name="an2882"></a>

<p>
When <code>fork()</code> is called, the current program is duplicated in memory,
thus creating a new process, and both processes continue their execution just
below the <code>fork()</code> system call. The two processes may, however, inspect the
return value of <code>fork()</code>: the return value in the original process (called
the <a name="an2883"></a>
<em>parent process</em>) differs from the return value in the newly created
process (called the <a name="an2884"></a>
<em>child process</em>):
    <ul>
    <li> In the <em>parent process</em> <code>fork()</code> returns the <a name="an2885"></a>
<em>process ID</em> of
the child process created by the <code>fork()</code> system call. This is a positive
integer value.
    <li> In the <em>child process</em> <code>fork()</code> returns 0.
    <li> If <code>fork()</code> fails, -1 is returned.
    </ul>
<p>
A basic <code>Fork</code> class should hide all bookkeeping details of a system
call like <code>fork()</code> from its users. The class <code>Fork</code> developed here will do
just that. The class itself only needs to take care of the proper execution of
the <code>fork()</code> system call. Normally, <code>fork()</code> is called to start a child
process, usually boiling down to the execution of a separate process. This
child process may expect input at its standard input stream and/or may
generate output to its standard output and/or standard error streams. <code>Fork</code>
does not know all this, and does not have to know what the child process will
do. However, <code>Fork</code> objects should be able to activate their child
processes.
<p>
Unfortunately, <code>Fork</code>'s constructor cannot know what actions its child
process should perform. Similarly, it cannot know what actions the parent
process should perform. For this particular situation, the
        <a name="an2886"></a>
<em>template method design pattern</em>
        <a name="an2887"></a>

    was developed. According to Gamma c.s., the <em>template method design
pattern</em>
    <blockquote>
    ``Define(s) the skeleton of an algorithm in an operation, deferring some
    steps to subclasses. (The) Template Method (design pattern) lets
    subclasses redefine certain steps of an algorithm, without changing
    the algorithm's structure.''
    </blockquote>
<p>
This design pattern allows us to define an <a name="an2888"></a>
<em>abstract base class</em>
        <a name="an2889"></a>

    already implementing the essential steps related to the <code>fork()</code> system
call and deferring the implementation of certain normally used parts of the
<code>fork()</code> system call to subclasses.
<p>
The <code>Fork</code> abstract base class itself has the following characteristics:
    <ul>
    <li> It defines a data member <code>d_pid</code>. This data member will contain
the child's <a name="an2890"></a>
<em>process id</em> (in the parent process) and the value 0 in the
child process. Its public interface declares but two members:
        <ul>
        <li> a <a name="an2891"></a>
<code>fork()</code> member function, performing the actual forking
            (i.e., it will create the (new) child process);
        <li> an <em>empty</em> <code>virtual</code> destructor <code>~Fork()</code>, which will be
        overridden by derived classes defining their own destructors.
                        <pre>
    inline Fork::~Fork()
    {}
</pre>
<p>
</ul>
        Here is <code>Fork</code>'s interface:
                    <pre>
    class Fork
    {
        int d_pid;

        public:
            virtual ~Fork();
            void fork();

        protected:
            int pid() const;
            virtual void childRedirections();
            virtual void parentRedirections();
            virtual void childProcess() = 0;    // both must be implemented
            virtual void parentProcess() = 0;
            int waitForChild();                 // returns the status
    };
</pre>
<p>
<li> All remaining member functions are declared in the class's
<code>protected</code> section and can thus <em>only</em> be used by derived classes. They
are:
        <ul>
        <li> The member function <code>pid()</code>, allowing derived classes to
            access the system <code>fork()</code>'s return value:
                        <pre>
    inline int Fork::pid() const
    {
        return d_pid;
    }
</pre>
<p>
<li> A member <code>int waitForChild()</code>, which can be called by parent
processes to wait for the completion of their child processes (as discussed
below). This member is declared in the class interface. Its implementation is
                <pre>
    #include "fork.ih"

    int Fork::waitForChild()
    {
        int status;

        waitpid(d_pid, &amp;status, 0);

        return WEXITSTATUS(status);
    }
</pre>
            This simple implementation returns the child's <a name="an2892"></a>
<em>exit status</em> to
the parent. The called system function <a name="an2893"></a>
<code>waitpid()</code> <em>blocks</em> until the
child terminates.
        <li> When <code>fork()</code> system calls are used,
    <em>parent processes</em> <a name="an2894"></a>
 and
    <a name="an2895"></a>
<em>child processes</em> <a name="an2896"></a>
 may always be distinguished. The
main distinction between these processes is that <code>d_pid</code> will be equal to
the child's process-id in the parent process, while <code>d_pid</code> will be equal to
0 in the child process itself. Since these two processes may always be
distinguished, they must be implemented by classes derived from <code>Fork</code>. To
enforce this requirement, the members <code>childProcess()</code>, defining the child
process' actions and <code>parentProcess()</code>, defining the parent process' actions
we defined as pure virtual functions:
            
        <li> In addition, communication between parent- and child processes
may use standard streams or other facilities, like <em>pipes</em> (cf. section
<a href="cplusplus20.html#PIPE">20.3.3</a>). To facilitate this inter-process communication, derived classes
<em>may</em> implement:
        <ul>
        <li><code>childRedirections()</code>: this member should be implemented if any
standard stream (<code>cin, cout</code>) or <code>cerr</code> must be redirected in the
<em>child</em> process (cf. section <a href="cplusplus20.html#REDIRECTION">20.3.1</a>);
        <li><code>parentRedirections()</code>: this member should be implemented if any
standard stream (<code>cin, cout</code>) or <code>cerr</code> must be redirected in the
<em>parent</em> process.
        </ul>
        Redirection of the standard streams will be necessary if parent- and
child processes should communicate with each other via the standard streams.
Here are their default definitions provided by the class's interface:
                    <pre>
    inline void Fork::childRedirections()
    {}
    inline void Fork::parentRedirections()
    {}
</pre>
<p>
</ul>
    </ul>
    The member function <code>fork()</code> calls the system function <code>fork()</code>
(Caution: since the system function <code>fork()</code> is called by a member
function having the same name, the <code>::</code> scope resolution operator must be
used to prevent a recursive call of the member function itself). After calling
<code>::fork()</code>, depending on its return value, either <code>parentProcess()</code>
or  <code>childProcess()</code> is called. Maybe redirection is
necessary. <code>Fork::fork()</code>'s implementation calls <code>childRedirections()</code>
just before calling <code>childProcess()</code>, and <code>parentRedirections()</code> just
before calling <code>parentProcess()</code>:
        <pre>
    #include "fork.ih"

    void Fork::fork()
    {
        if ((d_pid = ::fork()) &lt; 0)
            throw "Fork::fork() failed";

        if (d_pid == 0)                 // childprocess has pid == 0
        {
            childRedirections();
            childProcess();

            exit(1);                    // we shouldn't come here:
                                        // childProcess() should exit
        }

        parentRedirections();
        parentProcess();
    }
</pre>
    In <code>fork.cc</code> the class's <a name="an2897"></a>
<em>internal header file</em> <code>fork.ih</code> is
included. This header file takes care of the inclusion of the necessary system
header files, as well as the inclusion of <code>fork.h</code> itself. Its
implementation is:
        <pre>
    #include "fork.h"
    #include &lt;cstdlib&gt;
    #include &lt;unistd.h&gt;
    #include &lt;sys/types.h&gt;
    #include &lt;sys/wait.h&gt;
</pre>
<p>
Child processes should not return: once they have completed their tasks,
they should terminate. This happens automatically when the child process
performs a call to a member of the <a name="an2898"></a>
<code>exec...()</code> family, but if the child
itself remains active, then it must make sure that it terminates properly. A
child process normally uses <a name="an2899"></a>
<code>exit()</code> to terminate itself, but it should be
realized that <code>exit()</code> prevents the activation of destructors of objects
        <a name="an2900"></a>

        <a name="an2901"></a>

    defined at the same or more superficial nesting levels than the level at
which <code>exit()</code> is called. Destructors of globally defined objects <em>are</em>
activated when <code>exit()</code> is used. When using <code>exit()</code> to terminate
<code>childProcess()</code>, it should either itself call a support member function
defining all nested objects it needs, or it should define all its objects in a
compound statement (e.g., using a <code>throw</code> block) calling <code>exit()</code> beyond
the compound statement.
<p>
Parent processes should normally wait for their children to complete. The
terminating child processes inform their parent that they are about to
terminate by sending out a <a name="an2902"></a>
<em>signal</em> which should be caught by their
parents.  If child processes terminate and their parent processes do not catch
those signal then such child processes remain visible as so-called <a name="an2903"></a>
<em>zombie</em>
processes.
<p>
If parent processes must wait for their children to complete, they may
call the member <code>waitForChild()</code>. This member returns the exit status of a
child process to its parent.
<p>
There exists a situation where the <em>child</em> process <em>continues</em> to
live, but the <em>parent</em> dies. In nature this happens all the time: parents
tend to die before their children do. In our context (i.e. <strong>C++</strong>), this is
called a <a name="an2904"></a>
<em>daemon</em> program: the parent process dies and the child program
continues to run as a child of the basic <a name="an2905"></a>
<code>init</code> process. Again, when the
child eventually dies a signal is sent to its `step-parent' <a name="an2906"></a>

<code>init</code>. No zombie is created here, as <code>init</code> catches the termination
signals of all its <a name="an2907"></a>
 (step-) children.  The construction of a
daemon process is very simple, given the availability of the class <code>Fork</code>
(cf. section <a href="cplusplus20.html#DAEMON">20.3.2</a>).
<p>
<a name="REDIRECTION"></a><a name="l373"></a>
<h3>20.3.1: Redirection revisited</h3>
    <a name="concrete/redirection"></a>    Earlier, in section <a href="cplusplus05.html#REDIR">5.8.3</a>, it was noted that within a <strong>C++</strong>
program, streams could be <a name="an2908"></a>
 redirected using the
<a name="an2909"></a>
<code>ios::rdbuf()</code> member function. By assigning the <code>streambuf</code> of a stream
to another stream, both stream objects access the same <code>streambuf</code>, thus
realizing redirection at the level of the programming language itself.
<p>
It should be realized that this is fine within the context of the <strong>C++</strong>
program, but if that context is left, the redirection terminates, as the
operating system does not know about <code>streambuf</code> objects. This happens,
e.g., when a program uses a <a name="an2910"></a>
<code>system()</code> call to start a subprogram. The
program at the end of this section uses <strong>C++</strong> redirection to redirect the
information inserted into <a name="an2911"></a>
<code>cout</code> to a file, and then calls
        <pre>
    system("echo hello world")
</pre>
    to echo a well-known line of text. Since <code>echo</code> writes its information
to the standard output, this would be the program's redirected file if
<strong>C++</strong>'s redirection would be recognized by the operating system.
<p>
Actually, this doesn't happen; and <code>hello world</code> still appears at the
program's standard output instead of the redirected file. A solution of this
problem involves redirection at the operating system level, for which some
operating systems (e.g., <a name="an2912"></a>
Unix and friends) provide system calls like
<a name="an2913"></a>
<code>dup()</code> and <a name="an2914"></a>
<code>dup2()</code>. Examples of these system calls are given in section
<a href="cplusplus20.html#PIPE">20.3.3</a>.
<p>
Here is the example of the <em>failing redirection</em> at the system level
following  <strong>C++</strong> redirection using <code>streambuf</code> redirection:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;fstream&gt;
    #include &lt;cstdlib&gt;
    using namespace::std;

    int main()
    {
        ofstream of("outfile");

        cout.rdbuf(of.rdbuf());
        cout &lt;&lt; "To the of stream" &lt;&lt; endl;
        system("echo hello world");
        cout &lt;&lt; "To the of stream" &lt;&lt; endl;
    }
    /*
        Generated output: on the file `outfile'

        To the of stream
        To the of stream

        On standard output:

        hello world
    */
</pre>
<p>
<a name="DAEMON"></a><a name="l374"></a>
<h3>20.3.2: The `Daemon' program</h3>
    <a name="concrete/daemon"></a>    Applications exist in which the only purpose of <a name="an2915"></a>
<code>fork()</code> is to start a
child process. The parent process terminates immediately after spawning the
child process. If this happens, the child process continues to run as a child
process of <a name="an2916"></a>
<code>init</code>, the always running first process on <a name="an2917"></a>
Unix systems. Such
a process is often called a <a name="an2918"></a>
<em>daemon</em>, running as a <a name="an2919"></a>
background process.
<p>
Although the following example can easily be constructed as a plain <strong>C</strong>
program, it was included in the <strong>C++</strong> Annotations because it is so closely
related to the current discussion of the <code>Fork</code> class. I thought about
adding a <code>daemon()</code> member to that class, but eventually decided against it
because the construction of a daemon program is very simple and requires no
features other than those currently offered by the class <code>Fork</code>.  Here is an
example illustrating the construction of a daemon program:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;unistd.h&gt;
    #include "fork.h"

    class Daemon: public Fork
    {
        public:
            virtual void parentProcess()        // the parent does nothing.
            {}

            virtual void childProcess()
            {
                sleep(3);                       // actions taken by the child
                                                // just a message...
                std::cout &lt;&lt; "Hello from the child process\n";
                exit (0);                       // The child process exits.
            }
    };

    int main()
    {
        Daemon daemon;

        daemon.fork();          // program immediately returns
        return 0;
    }

    /*
        Generated output:
    The next command prompt, then after 3 seconds:
    Hello from the child process
    */
</pre>
<p>
<a name="PIPE"></a><a name="l375"></a>
<h3>20.3.3: The class `Pipe'</h3>
    <a name="concrete/pipes"></a>    Redirection at the system level involves the use of <a name="an2920"></a>
<em>file descriptors</em>,
created by the <a name="an2921"></a>
<code>pipe()</code> system call. When two processes want to communicate
using such file descriptors, the following takes place:
    <ul>
    <li> The process constructs two <em>associated file descriptors</em> using the
<code>pipe()</code> system call. One of the file descriptors is used for writing, the
other file descriptor is used for reading.
    <li> Forking takes place (i.e., the system <code>fork()</code> function is called),
duplicating the file descriptors. Now we have four file descriptors as both
the child process and the parent process have their own copies of the two
file descriptors created by <code>pipe()</code>.
    <li> One process (say, the parent process) will use the filedescriptors
for <em>reading</em>. It should close its filedescriptor intended for <em>writing</em>.
    <li> The other process (say, the child process) will use the
filedescriptors for <em>writing</em>. It should close its filedescriptor intended
for <em>reading</em>.
    <li> All information written by the child process to the file
descriptor intended for writing, can now be read by the parent process from
the corresponding file descriptor intended for reading, thus establishing a
communication channel between the child- and the parent process.
    </ul>
    Though basically simple, errors may easily creep in: purposes of file
descriptors available to the two processes (child- or parent-) may easily get
mixed up. To prevent bookkeeping errors, the bookkeeping may be properly set
up once, to be hidden therafter inside a class like the <code>Pipe</code> class
constructed here. Let's have a look at its characteristics (before the
implementations can be compiled, the compiler must have read the
class's header file as well as the file  <code>unistd.h</code>):
    <ul>
    <li> The <code>pipe()</code> system call expects a pointer to two <code>int</code> values,
which will represent, respectively, the file descriptors to use for accessing
the <em>reading end</em> and the <em>writing end</em> of the constructed pipe, after
<code>pipe()</code>'s successful completion. To avoid confusion, an <code>enum</code> is defined
associating these ends with symbolic constants. Furthermore, the class stores
the two file descriptors in a data member <code>d_fd</code>. Here is the class header
    and its private data:
                <pre>
    class Pipe
    {
        enum    RW { READ, WRITE };
        int     d_fd[2];
</pre>
<p>
<li> The class only needs a default constructor. This constructor
calls <code>pipe()</code> to create  a set of associated file descriptors used for
accessing both ends of a pipe:
                <pre>
    Pipe::Pipe()
    {
        if (pipe(d_fd))
            throw "Pipe::Pipe(): pipe() failed";
    }
</pre>
<p>
<li> The members <code>readOnly()</code> and <code>readFrom()</code> are used to configure
the pipe's reading end. The latter function is used to set up redirection, by
providing an alternate file descriptor which can be used to read from the
pipe. Usually this alternate file descriptor is <a name="an2922"></a>
<code>STDIN_FILENO</code>, allowing
<code>cin</code> to extract information from the pipe.  The former function is merely
used to configure the reading end of the pipe: it closes the matching writing
end, and returns a file descriptor that can be used to read from the pipe:
                <pre>
    int Pipe::readOnly()
    {
        close(d_fd[WRITE]);
        return d_fd[READ];
    }
    void Pipe::readFrom(int fd)
    {
        readOnly();

        redirect(d_fd[READ], fd);
        close(d_fd[READ]);
    }
</pre>
<p>
<li> <code>writeOnly()</code> and two <code>writtenBy()</code> members are available to
configure the writing end of a pipe. The former function is merely used to configure the writing end of the
pipe: it closes the matching reading end, and returns a file descriptor that
can be used to write to the pipe:
                <pre>
    int Pipe::writeOnly()
    {
        close(d_fd[READ]);
        return d_fd[WRITE];
    }
    void Pipe::writtenBy(int fd)
    {
        writtenBy(&amp;fd, 1);
    }
    void Pipe::writtenBy(int const *fd, size_t n)
    {
        writeOnly();

        for (size_t idx = 0; idx &lt; n; idx++)
            redirect(d_fd[WRITE], fd[idx]);

        close(d_fd[WRITE]);
    }
</pre>
<p>
For the latter member two overloaded versions are available:
        <ul>
        <li><code>writtenBy(int fileDescriptor)</code> is used to configure <em>single</em>
redirection, so that a specific file descriptor (usually <a name="an2923"></a>
<code>STDOUT_FILENO</code>
or <a name="an2924"></a>
<code>STDERR_FILENO</code>) may be used to write to the pipe;
        <li><code>(writtenBy(int *fileDescriptor, size_t n = 2))</code> may be used
to configure <em>multiple</em> redirection, providing an array argument containing
file descriptors. Information written to any of these file descriptors is
actually written into the pipe.
        </ul>
    <li> The class has one private data member, <code>redirect()</code>, which is used
to define a redirection using the <a name="an2925"></a>
<code>dup2()</code> system call. This function
expects two file descriptors. The first file descriptor represents a file
descriptor which can be used to access the device's information, the second
file descriptor is an alternate file descriptor which may also
be used to access the device's information once <code>dup2()</code> has completed
successfully. Here is <code>redirect()</code>'s implementation:
                <pre>
    void Pipe::redirect(int d_fd, int alternateFd)
    {
        if (dup2(d_fd, alternateFd) &lt; 0)
            throw "Pipe: redirection failed";
    }
</pre>
<p>
</ul>
    Now that redirection can be configured easily using one or more <code>Pipe</code>
objects, we'll now use <code>Fork</code> and <code>Pipe</code> in several demonstration
programs.
<p>
<a name="l376"></a>
<h3>20.3.4: The class `ParentSlurp'</h3>
    <a name="concrete/parentslurp"></a>    The class <a name="an2926"></a>
<code>ParentSlurp</code>, derived from <code>Fork</code>, starts a child process
which <em>execs</em> a program (like <code>/bin/ls</code>). The (standard) output of the
execed program is then read by the parent process. The parent process will
(for demonstration purposes) write the lines it receives to its standard
output stream, while prepending linenumbers to the received lines. It is most
convenient here to redirect the parents standard input stream, so that the
parent can read the <em>output</em> from the child process from its <code>std::cin</code>
<em>input</em> stream. Therefore, the only pipe that's used is used as an <em>input</em>
pipe at the parent, and an <em>output</em> pipe at the child.
<p>
The class <code>ParentSlurp</code> has the following characteristics:
    <ul>
    <li> It is derived from <code>Fork</code>. Before starting <code>ParentSlurp</code>'s class
interface, the compiler must have read both <code>fork.h</code> and
<code>pipe.h</code>. Furthermore, the class only uses one data member: a <code>Pipe</code>
object <code>d_pipe</code>.
    <li> Since <code>Pipe</code>'s constructor automatically constructs a pipe, and
since <code>d_pipe</code> is automatically constructed by <code>ParentSlurp</code>'s default
constructor, there is no need to define <code>ParentSlurp</code>'s constructor
explicitly. As no construtor needs to be implemented, all <code>ParentSlurp</code>'s
members can be declared as  <code>protected</code> members. Here is the class's
interface: 
                <pre>
    class ParentSlurp: public Fork
    {
        Pipe    d_pipe;

        protected:
            virtual void childRedirections();
            virtual void parentRedirections();
            virtual void childProcess();
            virtual void parentProcess();
    };
</pre>
<p>
<li> The <code>childRedirections()</code> member configures the pipe as a pipe for
reading. So, all information written to the child's standard output stream
will end up in the pipe. The big advantage of this all is that no streams
around file descriptors are needed to write to a file descriptor:
                <pre>
    inline void ParentSlurp::childRedirections()
    {
        d_pipe.writtenBy(STDOUT_FILENO);
    }
</pre>
<p>
<li> The <code>parentRedirections()</code> member, configures its end of the pipe
as a reading pipe. It does so by redirecting the reading end of the pipe to
its standard input file descriptor (<code>STDIN_FILENO</code>), thus allowing
extractions from <code>cin</code> instead of using streams built around file
descriptors.
                <pre>
    inline void ParentSlurp::parentRedirections()
    {
        d_pipe.readFrom(STDIN_FILENO);
    }
</pre>
<p>
<li> The <code>childProcess()</code> member only has to concentrate on its own
actions. As it only needs to execute a program (writing information to its
standard output), the member consists of but one statement:
                <pre>
    inline void ParentSlurp::childProcess()
    {
        execl("/bin/ls", "/bin/ls", static_cast&lt;char *&gt;(0));
    }
</pre>
<p>
<li> The <code>parentProcess()</code> member simply `slurps' the information
appearing at its standard input. Doing so, it actually reads the child's
output. It copies the received lines to its standard output stream after
having prefixed line numbers to them:
                <pre>
    void ParentSlurp::parentProcess()
    {
        std::string     line;
        size_t    nr = 1;

        while (getline(std::cin, line))
            std::cout &lt;&lt; nr++ &lt;&lt; ": " &lt;&lt; line &lt;&lt; std::endl;

        waitForChild();
    }
</pre>
<p>
</ul>
    The following program simply constructs a <code>ParentSlurp</code> object, and
calls its <code>fork()</code> member. Its output consists of a numbered list of files
in the directory where the program is started.  Note that the program also
needs the <code>fork.o, pipe.o</code> and <code>waitforchild.o</code> object files (see
earlier sources):
                <pre>
    int main()
    {
        ParentSlurp ps;

        ps.fork();
        return 0;
    }
    /*
        Generated Output (example only, actually obtained output may differ):

        1: a.out
        2: bitand.h
        3: bitfunctional
        4: bitnot.h
        5: daemon.cc
        6: fdinseek.cc
        7: fdinseek.h
        ...
    */
</pre>
<p>
<a name="l377"></a>
<h3>20.3.5: Communicating with multiple children</h3>
    <a name="concrete/children"></a>    The next step up the ladder is the construction of a child-process
monitor. Here, the parent process is responsible for all its child processes,
but it also must read their standard output. The user may enter information at
the parent process' standard input, for which a simple <a name="an2927"></a>
<em>command language</em>
is defined:
    <ul>
    <li><code>start</code> will start a new child process. The parent will return the ID
(a number) to the user. The ID may thereupon be used to send a message to that
particular child process
    <li><code>&lt;nr&gt; text</code> will send ``<code>text</code>'' to the child process having ID
<code>&lt;nr&gt;</code>;
    <li><code>stop &lt;nr&gt;</code> will terminate the child process having ID <code>&lt;nr&gt;</code>;
    <li><code>exit</code> will terminate the parent as well as all of its children.
    </ul>
    Furthermore, the child process that hasn't received text for some time
will complain, by sending a message to the parent-process. The parent process
will then simply transmit the received message to the user, by copying it to
the standard output stream.
<p>
A problem with programs like our monitor is that these programs allow
        <a name="an2928"></a>
<em>asynchronous input</em> from multiple sources: input may appear at the
standard input as well as at the input-sides of pipes. Also, multiple output
channels are used. To handle situations like these, the <a name="an2929"></a>
<code>select()</code> system
call was developed.
<p>
<a name="l378"></a>
<strong>20.3.5.1: The class `Select'</strong>
        <a name="concrete/select"></a>    The <a name="an2930"></a>
<code>select()</code> system call was developed to handle asynchronous
        <a name="an2931"></a>

        <a name="an2932"></a>
<em>I/O multiplexing</em>.
    This system call can be used to handle, e.g., input appearing
simultaneously at a set of file descriptors.
<p>
The <code>select()</code> system function is rather complex, and its full
discussion is beyond the <strong>C++</strong> Annotations' scope.
However, its use may be simplified by providing a <code>class Selector</code>,
hiding its details and offering an easy-to-use public interface. Here its
characteristics are discussed:
    <ul>
    <li> Most of <code>Select</code>'s members are very small, allowing us to define
most of its members as inline functions. The class requires quite a few data
members. Most of them of types that were specifically constructed for use by
<code>select()</code>. Therefore, before the class interface can be handled by the
compiler, various header files must have been read by it:
                <pre>
    #include &lt;limits.h&gt;
    #include &lt;unistd.h&gt;
    #include &lt;sys/time.h&gt;
    #include &lt;sys/types.h&gt;
</pre>
<p>
<li> The class definition and its data members may appear next. The data
type <code>fd_set</code> is a type designed to be used by <code>select()</code> and variables of
this type contain the set of filedescriptors on which <code>select()</code> has sensed
some activity. Furthermore, <code>select()</code> allows us to fire an
        <a name="an2933"></a>
<em>asynchronous alarm</em>. To specify alarm times, the class receives a
<a name="an2934"></a>
<code>timeval</code> data member. The remaining members are used by the class for
internal bookkeeping purposes, illustrated below. Here is the class's
interface: 
                <pre>
    class Selector
    {
        fd_set          d_read;
        fd_set          d_write;
        fd_set          d_except;
        fd_set          d_ret_read;
        fd_set          d_ret_write;
        fd_set          d_ret_except;
        timeval         d_alarm;
        int             d_max;
        int             d_ret;
        int             d_readidx;
        int             d_writeidx;
        int             d_exceptidx;

        public:
            Selector();

            int wait();
            int nReady();
            int readFd();
            int writeFd();
            int exceptFd();
            void setAlarm(int sec, int usec = 0);
            void noAlarm();
            void addReadFd(int fd);
            void addWriteFd(int fd);
            void addExceptFd(int fd);
            void rmReadFd(int fd);
            void rmWriteFd(int fd);
            void rmExceptFd(int fd);

        private:
            int checkSet(int *index, fd_set &amp;set);
            void addFd(fd_set *set, int fd);
    };
</pre>
<p>
</ul>
    The following member functions are part of the class's public interface:
    <ul>
    <li><a name="an2935"></a>
<code>Selector()</code>: the (default) constructor. It
clears the read, write, and execute <code>fd_set</code> variables, and switches off the
alarm. Except for <code>d_max</code>, the remaining data members do not require
initializations. Here is the implementation of <code>Selector</code>'s constructor:
                <pre>
    Selector::Selector()
    {
        FD_ZERO(&amp;d_read);
        FD_ZERO(&amp;d_write);
        FD_ZERO(&amp;d_except);
        noAlarm();
        d_max = 0;
    }
</pre>
<p>
<li><a name="an2936"></a>
<code>int wait()</code>: this member function will <em>block()</em>
until activity is sensed at any of the file descriptors monitored by
the <code>Selector</code> object, or if the <em>alarm</em> times out. It will throw an
exception when the <code>select()</code> system call itself fails. Here is <code>wait()</code>'s
implementation:
                <pre>
    int Selector::wait()
    {
        timeval t = d_alarm;

        d_ret_read = d_read;
        d_ret_write = d_write;
        d_ret_except = d_except;

        d_readidx = 0;
        d_writeidx = 0;
        d_exceptidx = 0;

        d_ret = select(d_max, &amp;d_ret_read, &amp;d_ret_write, &amp;d_ret_except, &amp;t);

        if (d_ret &lt; 0)
            throw "Selector::wait()/select() failed";

        return d_ret;
    }
</pre>
<p>
<li><a name="an2937"></a>
<code>int nReady</code>: this member function's return value
is defined only when <code>wait()</code> has returned. In that case it returns
0 for a alarm-timeout, -1 if <code>select()</code> failed, and the number of file
descriptors on which activity was sensed otherwise. It can be implemented
inline:
                <pre>
    inline int Selector::nReady()
    {
        return d_ret;
    }
</pre>
<p>
<li><a name="an2938"></a>
<code>int readFd()</code>: this member function's return
value also is defined only after <code>wait()</code> has returned. Its return value is
-1 if no (more) input file descriptors are available. Otherwise the next file
descriptor available for reading is returned. Its inline implementation is:
                <pre>
    inline int Selector::readFd()
    {
        return checkSet(&amp;d_readidx, d_ret_read);
    }
</pre>
<p>
<li><a name="an2939"></a>
<code>int writeFd()</code>: operating analogously to
<code>readFd()</code>, it returns the next file descriptor to which output is written.
Using <code>d_writeidx</code> and <code>d_ret_read</code>, it is implemented analogously to
<code>readFd()</code>;
    <li><a name="an2940"></a>
<code>int exceptFd()</code>: operating analogously to
<code>readFd()</code>, it returns the next exception file descriptor on which activity
was sensed.  Using <code>d_except_idx</code> and <code>d_ret_except</code>, it is implemented
analogously to <code>readFd()</code>;
    <li><a name="an2941"></a>
<code>void setAlarm(int sec, int usec = 0)</code>: this
member activates <code>Select</code>'s alarm facility. At least the number of seconds
to wait for the alarm to go off must be specified. It simply assigns values to
<code>d_alarm</code>'s fields. Then, at the next <code>Select::wait()</code> call, the alarm
will fire (i.e., <code>wait()</code> returns with return value 0) once the configured
alarm-interval has passed. Here is its (inline) implementation:
                <pre>
    inline void Selector::setAlarm(int sec, int usec)
    {
        d_alarm.tv_sec  = sec;
        d_alarm.tv_usec = usec;
    }
</pre>
<p>
<li><a name="an2942"></a>
<code>void noAlarm()</code>: this member switches off the
alarm, by simply setting the alarm interval to a very long period. Implemented
inline as:
                <pre>
    inline void Selector::noAlarm()
    {
        setAlarm(INT_MAX, INT_MAX);
    }
</pre>
<p>
<li><a name="an2943"></a>
<code>void addReadFd(int fd)</code>: this member adds a
file descriptor to the set of input file descriptors monitored by the
<code>Selector</code> object. The member function <code>wait()</code> will return once input is
available at the indicated file descriptor. Here is its inline implementation:
                <pre>
    inline void Selector::addReadFd(int fd)
    {
        addFd(&amp;d_read, fd);
    }
</pre>
<p>
<li><a name="an2944"></a>
<code>void addWriteFd(int fd)</code>: this member adds a
file descriptor to the set of output file descriptors monitored by the
<code>Selector</code> object. The member function <code>wait()</code> will return once output is
available at the indicated file descriptor. Using <code>d_write</code>, it is
implemented analogously as <code>addReadFd()</code>;
    <li><a name="an2945"></a>
<code>void addExceptFd(int fd)</code>: this member adds
a file descriptor to the set of exception file descriptors to be monitored by
the <code>Selector</code> object.  The member function <code>wait()</code> will return once
activity is sensed at the indicated file descriptor. Using <code>d_except</code>, it
is implemented analogously as <code>addReadFd()</code>;
    <li><a name="an2946"></a>
<code>void rmReadFd(int fd)</code>: this member removes a
file descriptor from the set of input file descriptors monitored by the
<code>Selector</code> object. Here is its inline implementation:
                <pre>
    inline void Selector::rmReadFd(int fd)
    {
        FD_CLR(fd, &amp;d_read);
    }
</pre>
<p>
<li><a name="an2947"></a>
<code>void rmWriteFd(int fd)</code>: this member removes a
file descriptor from the set of output file descriptors monitored by the
<code>Selector</code> object.  Using <code>d_write</code>, it is implemented analogously as
<code>rmReadFd()</code>;
    <li><a name="an2948"></a>
<code>void rmExceptFd(int fd)</code>: this member removes
a file descriptor from the set of exception file descriptors to be monitored
by the <code>Selector</code> object.  Using <code>d_except</code>, it is implemented analogously
as <code>rmReadFd()</code>;
    </ul>
    The class's remaining (two) members are support members, and should not be
used by non-member functions. Therefore, they should be declared in the class's
<code>private</code> section:
    <ul>
    <li> The member <code>addFd()</code> adds a certain file descriptor to a certain
<code>fd_set</code>. Here is its implementation:
                <pre>
    void Selector::addFd(fd_set *set, int fd)
    {
        FD_SET(fd, set);
        if (fd &gt;= d_max)
            d_max = fd + 1;
    }
</pre>
<p>
<li> The member <code>checkSet()</code> tests whether a certain file descriptor
(<code>*index</code>) is found in a certain <code>fd_set</code>. Here is its implementation:
                <pre>
    int Selector::checkSet(int *index, fd_set &amp;set)
    {
        int &amp;idx = *index;

        while (idx &lt; d_max &amp;&amp; !FD_ISSET(idx, &amp;set))
            ++idx;

        return idx == d_max ? -1 : idx++;
    }
</pre>
<p>
</ul>
<p>
<a name="MONITOR"></a><a name="l379"></a>
<strong>20.3.5.2: The class `Monitor'</strong>
        <a name="concrete/monitor"></a>    The <code>monitor</code> program uses a <code>Monitor</code> object to do most of the
work. The class has only one public constructor and one public member,
<code>run()</code>, to perform its tasks. Therefore, all other member functions
described below should be declared in the class's <code>private</code> section.
<p>
<code>Monitor</code> defines the <code>private enum Commands</code>, symbolically listing
the various commands its input language supports, as well as several data
members, among which a <code>Selector</code> object and a <code>map</code> using child order
numbers as its keys, and pointer to <code>Child</code> objects (see section <a href="cplusplus20.html#CHILD">20.3.5.3</a>)
as its values. Furthermore, <code>Monitor</code> has a static array member
<code>s_handler[]</code>, storing pointers to member functions handling user commands.
<p>
A destructor should have been implemented too, but its implementation is
left as an exercise to the reader. Before the class interface can be processed
by the compiler, it must have seen <code>select.h</code> and <code>child.h</code>. Here is the
class header, including the interface of the nested function object 
class <code>Find</code>:
                <pre>
    class Monitor
    {
        enum Commands
        {
            UNKNOWN,
            START,
            EXIT,
            STOP,
            TEXT,
            sizeofCommands
        };

        class Find
        {
            int     d_nr;
            public:
                Find(int nr);
                bool operator()(std::map&lt;int, Child *&gt;::value_type &amp;vt)
                                                                  const;
        };

        Selector                d_selector;
        int                     d_nr;
        std::map&lt;int, Child *&gt;  d_child;

        static void (Monitor::*s_handler[])(int, std::string const &amp;);

        public:
            enum Done
            {};

            Monitor();
            void run();

        private:
            static void killChild(std::map&lt;int, Child *&gt;::value_type it);
            static void initialize();

            Commands    next(int *value, std::string *line);
            void    processInput();
            void    processChild(int fd);

            void    createNewChild(int, std::string const &amp;);
            void    exiting(int = 0, std::string const &amp;msg = std::string());
            void    sendChild(int value, std::string const &amp;line);
            void    stopChild(int value, std::string const &amp;);
            void    unknown(int, std::string const &amp;);
    };
</pre>
<p>
Since there's only one non-class type data member, the class's constructor
remains very short and could be implemented inline. However, the array
<code>s_handler</code>, storing pointers to functions needs to be initialized as
well. This can be accomplished in several ways:
    <ul>
    <li> Since the <code>Command</code> enumeration only contains a fairly limited set
of commands, compile-time initialization could be considered:
                <pre>
    void (Monitor::*Monitor::s_handler[])(int, string const &amp;)  =
    {
        &amp;Monitor::unknown,              // order follows enum Command's
        &amp;Monitor::createNewChild,       // elements
        &amp;Monitor::exiting,
        &amp;Monitor::stopChild,
        &amp;Monitor::sendChild,
    };
</pre>
<p>
The advantage of this is that it's simple, and not requiring any run-time
effort. The disadvantage is of course relatively complex maintenance. If for
some reason <code>Commads</code> is modified, <code>s_handler</code> must be modified as
well. In cases like these, compile-time initialization is a little bit asking
for trouble. There is a simple alternative though, which admittedly 
does take some execution time:
    <li> A static member may be called before the first <code>Monitor</code> object is
constructed, which initializes the elements of the array explicitly. This has
the advantage of robustness against reordering of enumeration values, which is
important: enumerations <em>do</em> receive modifications during the development
cycle of a class.  Maintenance is still required if new values are added to
the enumeration, but in that case maintenance is required anyway.
    <li> Using a static member that's explicitly called from <code>main()</code> may
become a burden, or may be considered unacceptable, as it puts an additional
responsibility with the software engineer, rather than with the software. It's
a matter of taste whether that's a consideration to take seriously or not. If
the initialization function is not called, the program will clearly fail and
repairing the error caused by not calling the initialization function is
easily repaired. If that's considered bad practice, the initialization
function may be called from the class constructors as well. The following 
initialization function used in the current implementation of the class
<code>Monitor</code>:
                <pre>
    void (Monitor::*Monitor::s_handler[sizeofCommands])(int, string const &amp;);

    void Monitor::initialize()
    {
        if (s_handler[UNKNOWN] != 0)    // already initialized
            return;

        s_handler[UNKNOWN] =    &amp;Monitor::unknown;
        s_handler[START] =      &amp;Monitor::createNewChild;
        s_handler[EXIT] =       &amp;Monitor::exiting;
        s_handler[STOP] =       &amp;Monitor::stopChild;
        s_handler[TEXT] =       &amp;Monitor::sendChild;
    }
</pre>
<p>
</ul>   
    Since the initialization function immediately returns if the
initialization has already been performed, <code>Monitor</code>'s constructor may call
the initialization and still defensibly be implemented inline:
                <pre>
    inline Monitor::Monitor()
    :
        d_nr(0)
    {
        initialize();
    }
</pre>
<p>
The core of <code>Monitor</code>'s activities are performed by <code>run()</code>. It
performs the following tasks:
    <ul>
    <li> Initially, the <code>Monitor</code> object only listens to its standard
input: the set of input file descriptors to which <code>d_selector</code> will listen
is initialized to <code>STDIN_FILENO</code>.
    <li> Then, in a loop  <code>d_selector</code>'s <code>wait()</code> function is called.
If input on <code>cin</code> is available, it is processed by <code>processInput()</code>.
Otherwise, the input has arived from a child process. Information sent by
children is processed by <code>processChild()</code>.
    <li> To prevent <a name="an2949"></a>
<em>zombie</em><em>s</em>, the child processes must catch <em>their</em>
children's termination signals. This will be discussed below (In an earlier
version <code>Monitor</code> caught the termination signals. As noted by Ben Simons
(<code>ben at mrxfx dot com</code>) this is inappropriate: the child process itself has
that responsibility. Thanks, Ben).
    </ul>
    Here is <code>run()</code>'s implementation:
        <pre>
    #include "monitor.ih"

    void Monitor::run()
    {
        d_selector.addReadFd(STDIN_FILENO);

        while (true)
        {
            cout &lt;&lt; "? " &lt;&lt; flush;
            try
            {
                d_selector.wait();

                int fd;
                while ((fd = d_selector.readFd()) != -1)
                {
                    if (fd == STDIN_FILENO)
                        processInput();
                    else
                        processChild(fd);
                }
                cout &lt;&lt; "NEXT ...\n";

            }
            catch (char const *msg)
            {
                exiting(1, msg);
            }
        }
    }
</pre>
<p>
The member function <code>processInput()</code> reads the commands entered by the
user via the program's standard input stream. The member itself is rather
simple: it calls <code>next()</code> to obtain the next command entered by the user,
and then calls the corresponding function using the matching element of the
<code>s_handler[]</code> array. The members <code>processInput()</code> and
<code>next()</code> were defined as follows:
                <pre>
    void Monitor::processInput()
    {
        string line;
        int    value;
        Commands cmd = next(&amp;value, &amp;line);
        (this-&gt;*s_handler[cmd])(value, line);
    }
</pre>
<p>
        <pre>
    Monitor::Commands Monitor::next(int *value, string *line)
    {
        if (!getline(cin, *line))
            exiting(1, "Command::next(): reading cin failed");

        if (*line == "start")
            return START;

        if (*line == "exit" || *line == "quit")
        {
            *value = 0;
            return EXIT;
        }

        if (line-&gt;find("stop") == 0)
        {
            istringstream istr(line-&gt;substr(4));
            istr &gt;&gt; *value;
            return !istr ? UNKNOWN : STOP;
        }

        istringstream istr(line-&gt;c_str());
        istr &gt;&gt; *value;
        if (istr)
        {
            getline(istr, *line);
            return TEXT;
        }

        return UNKNOWN;
    }
</pre>
<p>
All other input sensed by <code>d_select</code> has been created by child
processes. Because <code>d_select</code>'s <code>readFd()</code> member returns the
corresponding input file descriptor, this descriptor can be passed to
<code>processChild()</code>. Then, using a <a name="an2950"></a>
<code>ifdstreambuf</code> (see section <a href="cplusplus20.html#IFDBUF">20.1.2.1</a>),
its information is read from an input stream. The <a name="an2951"></a>
<em>communication protocol</em>
used here is rather basic: To every line of input sent to a child, the child
sends exactly one line of text in return. Consequently, <code>processChild()</code>
just has to read one line of text:
                <pre>
    void Monitor::processChild(int fd)
    {
        ifdstreambuf ifdbuf(fd);
        istream istr(&amp;ifdbuf);
        string line;

        getline(istr, line);
        cout &lt;&lt; d_child[fd]-&gt;pid() &lt;&lt; ": " &lt;&lt; line &lt;&lt; endl;
    }
</pre>
<p>
Please note the construction <code>d_child[fd]-&gt;pid()</code> used in the above
source. <code>Monitor</code> defines the data member <code>map&lt;int, Child *&gt; d_child</code>.
This map contains the child's order number as its key, and a pointer to
the <code>Child</code> object as its value. A pointer is used here, rather than a
<code>Child</code> object, since we do want to use the facilities offered by the map,
but don't want to copy a <code>Child</code> object.
<p>
The implication of using pointers as <code>map</code>-values is of course that the
responsibility to destruct the <code>Child</code> object once it becomes superfluous
now lies with the programmer, and not any more with the run-time support
system.
<p>
Now that <code>run()</code>'s implementation has been covered, we'll concentrate on
the various commands users might enter:
    <ul>
    <li> When the <code>start</code> command is issued, a new child process is started.
A new element is added to <code>d_child</code> by the member <code>createNewChild()</code>.
Next, the <code>Child</code> object should start its activities, but the <code>Monitor</code>
object can not wait here for the child process to complete its activities, as
there is no well-defined endpoint in the near future, and the user will
probably want to enter more commands. Therefore, the <code>Child</code> process
will run as a <a name="an2952"></a>
<em>daemon</em>: its parent process will terminate immediately, and
its own child process will continue in the background. Consequently,
<code>createNewChild()</code> calls the child's <code>fork()</code> member. Although it is
the child's <code>fork()</code> function that is called, it is still the monitor
program wherein <code>fork()</code> is called. So, the <em>monitor</em> program is
duplicated by <code>fork()</code>. Execution then continues:
    <ul>
    <li> At the <code>Child</code>'s <code>parentProcess()</code> in its parent process;
    <li> At the <code>Child</code>'s <code>childProcess()</code> in its child process
    </ul>
    As the <code>Child</code>'s <code>parentProcess()</code> is an empty function, returning
immediately, the <code>Child</code>'s parent process effectively continues immediately
below <code>createNewChild()</code>'s <code>cp-&gt;fork()</code> statement.  As the child process
never returns (see section <a href="cplusplus20.html#CHILD">20.3.5.3</a>), the code below <code>cp-&gt;fork()</code> is never
executed by the <code>Child</code>'s child process. This is exactly as it should be.
<p>
In the parent process, <code>createNewChild()</code>'s remaining code simply
adds the file descriptor that's available for reading information from the
child to the set of input file descriptors monitored by <code>d_select</code>, and
uses <code>d_child</code> to  establish the association between that
file descriptor and the  <code>Child</code> object's address:
                <pre>
    void Monitor::createNewChild(int, string const &amp;)
    {
        Child *cp = new Child(++d_nr);

        cp-&gt;fork();

        int fd = cp-&gt;readFd();

        d_selector.addReadFd(fd);
        d_child[fd] = cp;

        cerr &lt;&lt; "Child " &lt;&lt; d_nr &lt;&lt; " started\n";
    }
</pre>
<p>
<li> Direct communication with the child is required for the <code>stop &lt;nr&gt;</code>
and <code>&lt;nr&gt; text</code> commands. The former command terminates child process
<code>&lt;nr&gt;</code>, by calling <code>stopChild()</code>. This function locates the child process
having the order number using an anonymous object of the class <code>Find</code>,
nested inside <code>Monitor</code>. The class <code>Find</code> simply compares the
provided <code>nr</code> with the children's order number returned by their <code>nr()</code>
members:
                <pre>
    inline Monitor::Find::Find(int nr)
    :
        d_nr(nr)
    {}
    inline bool Monitor::Find::operator()(
                            std::map&lt;int, Child *&gt;::value_type &amp;vt) const
    {
        return d_nr == vt.second-&gt;nr();
    }
</pre>
<p>
If the child process having order number <code>nr</code> was found, its file
descriptor is removed from <code>d_selector</code>'s set of input file
descriptors. Then the child process itself is terminated by the static member
<code>killChild()</code>. The member <code>killChild()</code> is declared as a <em>static</em> member
function, as it is used as function argument of the <code>for_each()</code> generic
algorithm by <code>erase()</code> (see below). Here is <code>killChild()</code>'s
implementation:
                <pre>
    void Monitor::killChild(map&lt;int, Child *&gt;::value_type it)
    {
        if (kill(it.second-&gt;pid(), SIGTERM))
            cerr &lt;&lt; "Couldn't kill process " &lt;&lt; it.second-&gt;pid() &lt;&lt; endl;
    }
</pre>
<p>
Having terminated the specified child process, the corresponding <code>Child</code>
object is destroyed and its pointer is removed from <code>d_child</code>:
                <pre>
    void Monitor::stopChild(int nr, string const &amp;)
    {
        map&lt;int, Child *&gt;::iterator it =
            find_if(d_child.begin(), d_child.end(), Find(nr));

        if (it == d_child.end())
            cerr &lt;&lt; "No child number " &lt;&lt; nr &lt;&lt; endl;
        else
        {
            d_selector.rmReadFd(it-&gt;second-&gt;readFd());

            delete it-&gt;second;
            d_child.erase(it);
        }
    }
</pre>
<p>
<li> The command <code>&lt;nr&gt; text&gt;</code> will send <code>text</code> to child process
<code>nr</code>, using the member function <code>sendChild()</code>. This function too, will
use a <code>Find</code> object to locate the process having order number <code>nr</code>, and
will then simply insert the text into the writing end of a pipe connected to
the indicated child process:
                <pre>
    void Monitor::sendChild(int nr, string const &amp;line)
    {
        map&lt;int, Child *&gt;::iterator it =
            find_if(d_child.begin(), d_child.end(), Find(nr));

        if (it == d_child.end())
            cerr &lt;&lt; "No child number " &lt;&lt; nr &lt;&lt; endl;
        else
        {
            ofdnstreambuf ofdn(it-&gt;second-&gt;writeFd());
            ostream out(&amp;ofdn);

            out &lt;&lt; line &lt;&lt; endl;
        }
    }
</pre>
<p>
<li> When users enter <code>exit</code> the member <code>exiting()</code> is called.
It terminates all child processes, by visiting
all elements of <code>d_child</code>, using the <a name="an2953"></a>
<code>for_each()</code> generic
algorithm (see section <a href="cplusplus17.html#FOREACH">17.4.17</a>). The program is subsequently terminated:
                <pre>
    void Monitor::exiting(int value, string const &amp;msg)
    {
        for_each(d_child.begin(), d_child.end(), killChild);
        if (msg.length())
            cerr &lt;&lt; msg &lt;&lt; endl;
        throw value;
    }
</pre>
<p>
</ul>
    Finally, the program's <code>main()</code> function is simply:
        <pre>
    #include "monitor.h"

    int main()
    try
    {
        Monitor monitor;

        monitor.run();
    }
    catch (int exitValue)
    {
        return exitValue;
    }

    /*
        Example of a session:

        # a.out
        ? start
        Child 1 started
        ? 1 hello world
        ? 3394: Child 1:1:  hello world
        ? 1 hi there!
        ? 3394: Child 1:2:  hi there!
        ? start
        Child 2 started
        ? 3394: Child 1: standing by
        ? 3395: Child 2: standing by
        ? 3394: Child 1: standing by
        ? 3395: Child 2: standing by
        ? stop 1
        ? 3395: Child 2: standing by
        ? 2 hello world
        ? 3395: Child 2:1:  hello world
        ? 1 hello world
        No child number 1
        ? exit3395: Child 2: standing by
        ?
        #
    */
</pre>
<p>
<a name="CHILD"></a><a name="l380"></a>
<strong>20.3.5.3: The class `Child'</strong>
        <a name="concrete/child"></a>    When the <code>Monitor</code> object starts a child process, it has to create an
object of the class <code>Child</code>. The <code>Child</code> class is derived from the class
<code>Fork</code>, allowing its construction as a <a name="an2954"></a>
<em>daemon</em>, as discussed in the
previous section. Since a <code>Child</code> object is a daemon, we know that its
parent process should be defined as an empty function.  its <code>childProcess()</code>
must of course still be defined. Here are the characteristics of the class
<code>Child</code>:
    <ul>
    <li> The <code>Child</code> class defines two <code>Pipe</code> data members, to allow
communications between its own child- and parent processes. As these pipes are
used by the <code>Child</code>'s child process, their names are aimed at the child
process: the child process reads from <code>d_in</code>, and writes to <code>d_out</code>. Here
is the interface of the class <code>Child</code>:
                <pre>
    class Child: public Fork
    {
        Pipe                d_in;
        Pipe                d_out;

        int         d_parentReadFd;
        int         d_parentWriteFd;
        int         d_nr;

        public:
            Child(int nr);
            virtual ~Child();
            int readFd() const;
            int writeFd() const;
            int pid() const;
            int nr() const;
            virtual void childRedirections();
            virtual void parentRedirections();
            virtual void childProcess();
            virtual void parentProcess();
    };
</pre>
<p>
<li> The <code>Child</code>'s constructor simply stores its argument, a
child-process order number, in its own <code>d_nr</code> data member:
                <pre>
    inline Child::Child(int nr)
    :
        d_nr(nr)
    {}
</pre>
<p>
<li> The <code>Child</code>'s child process will simply obtain its information from
its standard input stream, and it will write its information to its standard
output stream. Since the communication channels are pipes, redirections must
be configured. The <code>childRedirections()</code>
member is implemented as follows:
                <pre>
    void Child::childRedirections()
    {
        d_in.readFrom(STDIN_FILENO);
        d_out.writtenBy(STDOUT_FILENO);
    }
</pre>
<p>
<li> Although the parent process performs no actions, it must configure
some redirections. Since the names of the pipes indicate their functions in
the child process, <code>d_in</code> is used for <em>writing</em> by the parent, and
<code>d_out</code> is used for <em>reading</em> by the parent. Here is the implementation of
<code>parentRedirections()</code>:
                <pre>
    void Child::parentRedirections()
    {
        d_parentReadFd = d_out.readOnly();
        d_parentWriteFd = d_in.writeOnly();
    }
</pre>
<p>
<li> The <code>Child</code> object will exist until it is destroyed by the
<code>Monitor</code>'s <code>stopChild()</code> member. By allowing its creator, the <code>Monitor</code>
object, to access the parent-side ends of the pipes, the <code>Monitor</code> object
can communicate with the <code>Child</code>'s child process via those pipe-ends. The
members <code>readFd()</code> and <code>writeFd()</code> allow the <code>Monitor</code> object to access
these pipe-ends:
                <pre>
    inline int Child::readFd() const
    {
        return d_parentReadFd;
    }
    inline int Child::writeFd() const
    {
        return d_parentWriteFd;
    }
</pre>
<p>
<li> The <code>Child</code> object's child process basically has two tasks to
perform:
        <ul>
        <li> It must reply to information appearing at its standard input
stream;
        <li> If no information has appeared within a certain time frame (the
implementations uses an interval of five seconds), then a message should be
written to its standard output stream anyway.
        </ul>
        To implement this behavior, <code>childProcess()</code> defines a local
<code>Selector</code> object, adding <code>STDIN_FILENO</code> to its set of monitored input
file descriptors.
<p>
Then, in an eternal loop, <code>childProcess()</code> waits for <code>selector.wait()</code>
to return. When the alarm goes off, it sends a message to its standard output.
(Hence, into the writing pipe). Otherwise, it will echo the messages appearing
at its standard input to its standard output. Here is the implementation of
the <code>childProcess()</code> member:
                <pre>
    void Child::childProcess()
    {
        Selector    selector;
        size_t    message = 0;

        selector.addReadFd(STDIN_FILENO);
        selector.setAlarm(5);

        while (true)
        {
            try
            {
                if (!selector.wait())       // timeout
                    cout &lt;&lt; "Child " &lt;&lt; d_nr &lt;&lt; ": standing by\n";
                else
                {
                    string  line;
                    getline(cin, line);
                    cout &lt;&lt; "Child " &lt;&lt; d_nr &lt;&lt; ":" &lt;&lt; ++message &lt;&lt; ": " &lt;&lt;
                                                        line &lt;&lt; endl;
                }
            }
            catch (...)
            {
                    cout &lt;&lt; "Child " &lt;&lt; d_nr &lt;&lt; ":" &lt;&lt; ++message &lt;&lt; ": " &lt;&lt;
                                "select() failed" &lt;&lt; endl;
            }
        }
        exit(0);
    }
</pre>
<p>
<li> Next, twoaccessors allow the <code>Monitor</code> object to obtain the
<code>Child</code>'s process ID and order number, respectively:
                <pre>
    inline int Child::pid() const
    {
        return Fork::pid();
    }
    inline int Child::nr() const
    {
        return d_nr;
    }
</pre>
<p>
<li> A <code>Child</code> process terminates when the user enters a <code>stop</code>
command. When an existing child process number was entered, the corresponding
<code>Child</code> object is removed from <code>Monitor</code>'s <code>d_child</code> map. As a result,
its destructor is called. In its turn, <code>Child</code>'s destructor will call
<code>kill</code> to terminate its child, and then waits for the child to
terminate. Once the child has terminated, the destructor has completed its
work as well and returns, competing the erasure from <code>d_child</code>. The
implementation offered here will fail if the child process doesn't react to
the <code>SIGTERM</code> signal. In this demonstration program this does not happen. In
`real life' implementations more elaborate killing-procedures may be required
(e.g., using <code>SIGKILL</code> in addition to <code>SIGTERM</code>). As discussed in section
<a href="cplusplus08.html#CONSEXCEPTIONS">8.8</a> it is important to ensure that the destruction
succeeds. Here is the implementation of the <code>Child</code>'s destructor:
                <pre>
    Child::~Child()
    {
        if (pid())
        {
            cout &lt;&lt; "Killing process " &lt;&lt; pid() &lt;&lt; "\n";
            kill(pid(), SIGTERM);
            int status;
            wait(&amp;status);
        }
    }
</pre>
<p>
</ul>
<p>
<a name="BITFUN"></a><a name="l381"></a>
<h2>20.4: Function objects performing bitwise operations</h2>
<a name="concrete/bitwise"></a>    In section <a href="cplusplus17.html#PREDEFINED">17.1</a> several types of <a name="an2955"></a>
predefined function objects
were introduced. Predefined function objects performing
    <a name="an2956"></a>
arithmetic operations, <a name="an2957"></a>
relational operations, and
    <a name="an2958"></a>
logical operations exist, corresponding to a multitude of
    <a name="an2959"></a>
 binary- and <a name="an2960"></a>
 unary operators.
<p>
Some operators appear to be missing: there appear to be no predefined
function objects corresponding to <a name="an2961"></a>
bitwise operations. However, their
construction is, given the available predefined function objects, not
difficult. The following examples show a <a name="an2962"></a>
template class implementing a
function object calling the <a name="an2963"></a>
bitwise and (<a name="an2964"></a>
<code>operator&amp;()</code>), and a template
class implementing a function object calling the <a name="an2965"></a>
unary not
(<a name="an2966"></a>
<code>operator~()</code>). It is left to the reader to construct similar function
objects for other operators.
<p>
Here is the implementation of a function object calling the <a name="an2967"></a>
bitwise
<code>operator&amp;()</code>:
        <pre>
    #include &lt;functional&gt;

    template &lt;typename _Tp&gt;
    struct bit_and: public std::binary_function&lt;_Tp, _Tp, _Tp&gt;
    {
        _Tp operator()(_Tp const &amp;__x, _Tp const &amp;__y) const
        {
            return __x &amp; __y;
        }
    };
</pre>
<p>
Here is the implementation of a function object calling <code>operator~()</code>:
        <pre>
    #include &lt;functional&gt;

    template &lt;typename _Tp&gt;
    struct bit_not: public std::unary_function&lt;_Tp, _Tp&gt;
    {
        _Tp operator()(_Tp const &amp;__x) const
        {
            return ~__x;
        }
    };
</pre>
<p>
These and other <a name="an2968"></a>
missing predefined function objects
        <a name="an2969"></a>
 are also implemented in the
file <a name="an2970"></a>
<code>bitfunctional</code>, which is found in the <code>cplusplus.yo.zip</code> archive. It
should be noted that these classes are derived from existing template classes
(e.g., <a name="an2971"></a>
<code>std::binary_function</code> and <a name="an2972"></a>
<code>std::unary_function</code>). These base
classes offer several typedefs which are expected (used) by various generic
algorithms as defined in the STL (cf. chapter <a href="cplusplus17.html#STL">17</a>), thus following the
advice offered in, e.g., the <strong>C++</strong> header file <a name="an2973"></a>
<code>bits/stl_function.h</code>:
        <pre>
   *  The standard functors are derived from structs named unary_function
   *  and binary_function.  These two classes contain nothing but typedefs,
   *  to aid in generic (template) programming.  If you write your own
   *  functors, you might consider doing the same.
</pre>
<p>
Here is an example using <code>bit_and()</code> removing all odd numbers from a
vector of <code>int</code> values:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;algorithm&gt;
    #include &lt;vector&gt;
    #include "bitand.h"
    using namespace std;

    int main()
    {
        vector&lt;int&gt; vi;

        for (int idx = 0; idx &lt; 10; ++idx)
            vi.push_back(idx);

        copy
        (
            vi.begin(),
            remove_if(vi.begin(), vi.end(), bind2nd(bit_and&lt;int&gt;(), 1)),
            ostream_iterator&lt;int&gt;(cout, " ")
        );
        cout &lt;&lt; endl;
    }
    /*
        Generated output:

        0 2 4 6 8
    */
</pre>
<p>
<a name="CONCRETEITER"></a><a name="l382"></a>
<h2>20.5: Implementing a `reverse_iterator'</h2>
<a name="concrete/iterators"></a>    Earlier, in section <a href="cplusplus19.html#RANDOMIT">19.12.1</a>, the construction of iterators and
reverse iteraters was discussed. In that section the iterator was constructed
as an inner class in a class derived from a vector of pointers to strings.
<p>
An object of this nested iterator class handled the dereferencing of the
pointers stored in the vector. This allowed us to sort the <em>strings</em>
pointed to by the vector's elements rather than the <em>pointers</em>.
<p>
A drawback of the approach taken in section <a href="cplusplus19.html#RANDOMIT">19.12.1</a> is that the
class implementing the iterator is closely tied to the derived class as the
iterator class was implemented as a nested class. What if we would like to
provide any class derived from a container class storing pointers with an
iterator handling the pointer-dereferencing?
<p>
In this section a variant to the earlier (nested class) approach is
discussed. The iterator class will be defined as a <a name="an2974"></a>
<em>template class</em>,
    <a name="an2975"></a>

    parameterizing the data type to which the container's elements point as
well as the iterator type of the container itself. Once again, we will
implement a <a name="an2976"></a>
<em>RandomIterator</em> as it is the most complex iterator type.
<p>
Our class is named <code>RandomPtrIterator</code>, indicating that it is a random
iterator operating on pointer values. The template class defines three
template type parameters:
    <ul>
    <li> The first parameter specifies the derived class type
(<code>Class</code>). Like the earlier nested class, <code>RandomPtrIterator</code>'s
constructor will be private. Therefore we need <code>friend</code> declarations to
allow client classes to construct <code>RandomPtrIterators</code>.  However, a
<code>friend class Class</code> cannot be defined: template parameter types cannot be
used in <code>friend class ...</code> declarations. But this is no big problem: not
every member of the client class needs to construct iterators. In fact, only
<code>Class</code>'s <code>begin()</code> and <code>end()</code> members must be able to construct
iterators. Using the template's first parameter, friend declarations can be
specified for the client's <code>begin()</code> and <code>end()</code> members.
    <li> The second template parameter parameterizes the container's iterator
type (<code>BaseIterator</code>);
    <li> The third template parameter indicates the data type to which the
pointers point (<code>Type</code>).
    </ul>
    <code>RandomPtrIterator</code> uses one private data
element, a <code>BaseIterator</code>. Here is the class interface, including the 
constructor's implementation:
                <pre>
    #include &lt;iterator&gt;

    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    class RandomPtrIterator:
          public std::iterator&lt;std::random_access_iterator_tag, Type&gt;
    {
        friend RandomPtrIterator&lt;Class, BaseIterator, Type&gt; Class::begin();
        friend RandomPtrIterator&lt;Class, BaseIterator, Type&gt; Class::end();

        BaseIterator d_current;

        RandomPtrIterator(BaseIterator const &amp;current);

        public:
            bool operator!=(RandomPtrIterator const &amp;other) const;
            int operator-(RandomPtrIterator const &amp;rhs) const;
            RandomPtrIterator const operator+(int step) const;
            Type &amp;operator*() const;
            bool operator&lt;(RandomPtrIterator const &amp;other) const;
            RandomPtrIterator &amp;operator--();
            RandomPtrIterator const operator--(int);
            RandomPtrIterator &amp;operator++();
            RandomPtrIterator const operator++(int);
            bool operator==(RandomPtrIterator const &amp;other) const;
            RandomPtrIterator const operator-(int step) const;
            RandomPtrIterator &amp;operator-=(int step);
            RandomPtrIterator &amp;operator+=(int step);
            Type *operator-&gt;() const;
    };

    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    RandomPtrIterator&lt;Class, BaseIterator, Type&gt;::RandomPtrIterator(
                                    BaseIterator const &amp;current)
    :
        d_current(current)
    {}
</pre>
<p>
Dissecting its <code>friend</code> declarations, we see that the members
<code>begin()</code> and <code>end()</code> of a class <code>Class</code>, returning a
<code>RandomPtrIterator</code> object for the types <code>Class, BaseIterator</code> and
<code>Type</code> are granted access to <code>RandomPtrIterator</code>'s  private constructor.
That is exactly what we want. Note that <code>begin()</code> and <code>end()</code> are declared
as <a name="an2977"></a>
<em>bound friend</em><em>s</em>.
<p>
All <code>RandomPtrIterator</code>'s remaining members are public. Since
<code>RandomPtrIterator</code> is just a generalization of the nested class
<code>iterator</code> developed in section <a href="cplusplus19.html#RANDOMIT">19.12.1</a>, re-implementing the required
member functions is easy, and only requires us to change <code>iterator</code> into
<code>RandomPtrIterator</code> and to change <code>std::string</code> into <code>Type</code>. For
example, <code>operator&lt;()</code>, defined in the class <code>iterator</code> as
                <pre>
inline bool StringPtr::iterator::operator&lt;(iterator const &amp;other) const
{
    return **d_current &lt; **other.d_current;
}
</pre>
<p>
is re-implemented as:
                <pre>
    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    bool RandomPtrIterator&lt;Class, BaseIterator, Type&gt;::operator&lt;(
                                    RandomPtrIterator const &amp;other) const
    {
        return **d_current &lt; **other.d_current;
    }
</pre>
<p>
As a second example: <code>operator*()</code>, defined in the class
<code>iterator</code> as
                <pre>
inline std::string &amp;StringPtr::iterator::operator*() const
{
    return **d_current;
}
</pre>
<p>
is re-implemented as:
                <pre>
    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    Type &amp;RandomPtrIterator&lt;Class, BaseIterator, Type&gt;::operator*() const
    {
        return **d_current;
    }
</pre>
<p>
The pre- and postfix increment operators are re-implemented as:
                <pre>
    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    RandomPtrIterator&lt;Class, BaseIterator, Type&gt;
    &amp;RandomPtrIterator&lt;Class, BaseIterator, Type&gt;::operator++()
    {
        ++d_current;
        return *this;
    }
    template &lt;typename Class, typename BaseIterator, typename Type&gt;
    RandomPtrIterator&lt;Class, BaseIterator, Type&gt; const
    RandomPtrIterator&lt;Class, BaseIterator, Type&gt;::operator++(int)
    {
        return RandomPtrIterator(d_current++);
    }
</pre>
<p>
Remaining members can be implemented accordingly, their actual
implementations are left as an exercise to the reader (or can be obtained from
the <code>cplusplus.yo.zip</code> archive, of course).
<p>
Reimplementing the class <code>StringPtr</code> developed in section <a href="cplusplus19.html#RANDOMIT">19.12.1</a>
is not difficult either. Apart from including the header file defining the
template class <code>RandomPtrIterator</code>, it requires only a single modification
as its <code>iterator</code> typedef must now be associated with a
<code>RandomPtrIterator</code>. Here are the full class interface and inline member
definitions: 
        <pre>
    #ifndef _INCLUDED_STRINGPTR_H_
    #define _INCLUDED_STRINGPTR_H_

    #include &lt;vector&gt;
    #include &lt;string&gt;
    #include "iterator.h"

    class StringPtr: public std::vector&lt;std::string *&gt;
    {
        public:
            typedef RandomPtrIterator
                    &lt;
                        StringPtr,
                        std::vector&lt;std::string *&gt;::iterator,
                        std::string
                    &gt;
                        iterator;

            typedef std::reverse_iterator&lt;iterator&gt; reverse_iterator;

            iterator begin();
            iterator end();
            reverse_iterator rbegin();
            reverse_iterator rend();
    };

    inline StringPtr::iterator StringPtr::begin()
    {
        return iterator(this-&gt;std::vector&lt;std::string *&gt;::begin() );
    }
    inline StringPtr::iterator StringPtr::end()
    {
        return iterator(this-&gt;std::vector&lt;std::string *&gt;::end());
    }
    inline StringPtr::reverse_iterator StringPtr::rbegin()
    {
        return reverse_iterator(end());
    }
    inline StringPtr::reverse_iterator StringPtr::rend()
    {
        return reverse_iterator(begin());
    }
    #endif
</pre>
<p>
Including <code>StringPtr</code>'s modified header file into the program given in
section <a href="cplusplus19.html#REVERSEIT">19.12.2</a> will result in a program behaving identically to its
earlier version, albeit that <code>StringPtr::begin()</code> and <code>StringPtr::end()</code>
now return iterator objects constructed from a template definition.
<p>
<a name="A2X"></a><a name="l383"></a>
<h2>20.6: A text to anything converter</h2>
<a name="concrete/a2x"></a>    The standard <strong>C</strong> library offers conversion functions like <a name="an2978"></a>
<code>atoi()</code>,
<code>atol()</code>, and other functions, which can be used to convert <a name="an2979"></a>
<code>ASCII-Z</code>
strings to numerical values. In <strong>C++</strong>, these functions are still available,
but a more <em>type safe</em> way to convert text to other types  is by using
objects of the class <code>std::istringsteam</code>.
<p>
Using the <code>std::istringstream</code> class instead of the <strong>C</strong> standard
conversion functions may have the advantage of type-safety, but it also
appears to be a rather cumbersome alternative. After all, we will have to
construct and initialize a <code>std::istringstream</code> object first, before we're
actually able to extract a value of some type from it. This requires us to use
a variable. Then, if the extracted value is actually only needed to
initialize some function-parameter, one might wonder whether the additional
variable and the <code>istringstream</code> construction can somehow be avoided.
<p>
In this section we'll develop a class (<a name="an2980"></a>
<code>A2x</code>) preventing all the
disadvantages of the standard <strong>C</strong> library functions, without requiring the
cumbersome definitions of <code>std::istringstream</code> objects over and over
again. The class is called <code>A2x</code> for
    `<a name="an2981"></a>
ascii to anything'.
<p>
<code>A2x</code> objects can be used to obtain a value for any type extractable
from <code>std::istream</code> objects given its textual representation. Since <code>A2x</code>
represents the object-variant of the <strong>C</strong> functions, it is not only type-safe
but <em>also</em> extensible. Consequently, their use is greatly preferred over the
standard <strong>C</strong> functions. Here are its characteristics:
    <ul>
    <li>  <code>A2x</code> is derived from <code>std::istringstream</code>, so all members
of the class <code>std::istringstream</code> are available. Thus, extractions of values
of variables can always be performed effortlessly. Here's the class's
interface: 
                <pre>
class A2x: public std::istringstream
{
    public:
        A2x();
        A2x(char const *txt);
        A2x(std::string const &amp;str);

        template &lt;typename T&gt;
        operator T();

        A2x &amp;operator=(char const *txt);

        A2x &amp;operator=(std::string const &amp;str);
        A2x &amp;operator=(A2x const &amp;other);
};
</pre>
<p>
<li> <code>A2x</code> has a default constructor and a constructor expecting a
<code>std::string</code> argument. The latter constructor may be used to initialize
<code>A2x</code> objects with text to be converted (e.g., a line of text obtained from
reading a configuration file):
                <pre>
inline A2x::A2x()
{}

inline A2x::A2x(char const *txt)                    // initialize from text
:
    std::istringstream(txt)
{}

inline A2x::A2x(std::string const &amp;str)
:
    std::istringstream(str.c_str())
{}
</pre>
<p>
<li> <code>A2x</code>'s real strength comes from its <code>operator Type()</code> conversion
member template. As it is a member template, it will automatically adapt
itself to the type of the variable that should be given a value, obtained by
converting the text stored inside the <code>A2x</code> object to the variable's
type. When the extraction fails, <code>A2x</code>'s inherited <code>good()</code> member will
return <code>false</code>:
                <pre>
template &lt;typename Type&gt;
inline A2x::operator Type()
{
    Type t;

    return (*this &gt;&gt; t) ? t : Type();
}
/=
inline A2x &amp;A2x::operator=(std::string const &amp;str)
{
    return operator=(str.c_str());
}
//OP=
inline A2x &amp;A2x::operator=(A2x const &amp;other)
{
    return operator=(other.str());
}
</pre>
<p>
<li> Occasionally, the compiler may not be able to determine which type to
convert to. In that case, an <em>explicit template type</em> can be used:
        <pre>
            A2x.operator int&lt;int&gt;();
            // or just:
            A2x.operator int();
</pre>
        Since neither syntax looks attractive, the member template
<code>to()</code> was provided as well, allowing constructions like:
            <pre>
        A2x.to(int());
</pre>
        Here is its implementation:
            
    <li> Once an <code>A2x</code> object is available, it may be reinitialized using
its <code>operator=()</code> member:
            <pre>
#include "a2x.h"

A2x &amp;A2x::operator=(std::string const &amp;txt)
{
    clear();        // very important!!! If a conversion failed, the object
                    // remains useless until executing this statement
    str(txt);
    return *this;
}
</pre>
    </ul>
<p>
Here are some examples of its use:
        <pre>
    int x = A2x("12");          // initialize int x from a string "12"
    A2x a2x("12.50");           // explicitly create an A2x object

    double d;
    d = a2x;                    // assign a variable using an A2x object

    a2x = "err";
    d = a2x;                    // d is 0: the conversion failed,
                                // and a2x.good() == false

    a2x = " a";                 // reassign a2x to new text
    char c = a2x;               // c now 'a': internally operator&gt;&gt;() is used
                                // so initial blanks are skipped.

    extern expectsInt(int x);   // initialize a parameter using an
    expectsInt(A2x("1200"));    // anonymous A2x object

    d = A2x("12.45").to(int()); // d is 12, not 12.45
</pre>
    Apart from a class <code>A2x</code> a complementary class (<a name="an2982"></a>
<code>X2a</code>) can easily be
constructed as well. The construction of <code>X2a</code> is left as an exercise to
the reader.
<p>
<a name="STLWRAPPERS"></a><a name="l384"></a>
<h2>20.7: Wrappers for STL algorithms</h2>
<a name="concrete/wrappers"></a>    Many generic algorithms (cf. chapter <a href="cplusplus17.html#STL">17</a>) use function objects to
operate on the data to which their iterators refer, or they require predicate
function objects using some criterion to make a decision about these data. The
standard approach followed by the generic algorithms is to pass the
information to which the iterators refer to overloaded function call operators
(i.e., <a name="an2983"></a>
<code>operator()()</code>) of function objects that are passed as arguments to
the generic algorithms.
<p>
Usually this approach requires the construction of a dedicated class
implementing the required function object. However, in many cases the <em>class
context</em> in which the iterators exist already offers the required
functionality. Alternatively, the functionality might exist as member function
of the objects to which the iterators refer. For example, finding the first
empty <code>string</code> object in a vector of <code>string</code> objects could profitably use
the <code>string::empty()</code> member.
<p>
Another frequently encountered situation is related to a
    <a name="an2984"></a>
<em>local context</em>. Once again, consider the situation where the elements
of a <code>string</code> vector are all visited: each object must be inserted in a
stream whose reference is only known to the function in which the <code>string</code>
elements are visited, but some additional information must be passed to the
insertion function as well, making the use of the <code>ostream_inserter</code> less
appropriate.
<p>
The frustrating part of using generic algorithms is that these dedicated
function objects often very much look like each other, but the standard
solution (using  predefined function objects, using specialized iterators)
seldomly do the required job: their fixed function interfaces (e.g.,
<code>equal_to</code> calling the object's <code>operator==()</code>) often are too rigid to be
useful and, furthermore, they are unable to use any additional local
context that is active when they are used.
<p>
Nevertheless, one may wonder whether template classes might be constructed
which can be used again and again to create dedicated function objects. Such
template class instantiations should offer facilities to call configurable
(member) functions, using a configurable local context.
<p>
In the upcoming sections, several <a name="an2985"></a>
<em>wrapper templates</em>
        <a name="an2986"></a>
 supporting these requirements are
developed. To support a <em>local context</em>, a dedicated <em>local context struct</em>
is introduced. Furthermore, the wrapper templates will allow us to specify the
member function that should be called in its constructor. Thus the rigidness
of the fixed member function as used in the predefined function objects is
avoided.
<p>
As an example of a generic algorithm usually requiring a simple function
object, consider <code>for_each()</code>. The <code>operator()()</code> of the function object
passed to this algorithm receives as its argument a reference to the object to
which the iterators refer. Generally, the <code>operator()()</code> will do one of two
things:
    <ul>
    <li> It may call a member function of the object defined in its parameter
list (e.g., <code>operator()(string &amp;str)</code> may call <code>str.length()</code>);
    <li> It may call a function, passing it its parameter as argument (e.g.,
calling <code>somefunction(str)</code>).
    </ul>
    Of course, the latter example is a bit overkill, since
<code>somefunction()</code>'s address could actually directly have been passed to the
generic algorithm, so why use this complex procedure? The answer is
<em>context</em>: if <code>somefunction()</code> would actually require other arguments,
representing the local context in which <code>somefunction()</code> was called, then
the function object's constructor could have received the local context as its
arguments, passing that local context on to <code>somefunction()</code>, together with
the object received by the function object's <code>operator()()</code> function. There
is no way to pass any local context to the generic algorithm's simple variant,
in which a function's address is passed to the generic function.
<p>
At first sight, however, the fact that a local context differs from one
situation to another makes it hard to standardize the local context: a local
context might consist of values, pointers, references, which differ in number
and types from one situation to another. Defining templates for all possible
situations is clearly impractical, and using <strong>C</strong>-style <a name="an2987"></a>
variadic functions
is also not very attractive, since the arguments passed to a variadic function
object constructor cannot simply be passed on to the function object's
<code>operator()()</code>.
<p>
The concept of a <a name="an2988"></a>
<em>local context struct</em> is introduced to standardize
the local context. It is based on the following considerations:
    <ul>
    <li> Usually, a function requiring a local context is a member
function of some class.
    <li> Instead of using the intuitive implementation where the member
function is given the required parameters representing a local context, it
receives a single argument: a <code>const &amp;</code> to a local context <code>struct</code>.
    <li> The local context <code>struct</code> is defined in the function's class
interface.
    <li> Before the function is called, a local context <code>struct</code> is
initialized, which is then passed as argument to the function.
    </ul>
    Of course, the organization of local context <code>struct</code>s will differ from
one situation to the next situation, but there is always just <em>one</em> local
context required. The fact that the inner organization of the local context
differs from one situation to the next causes no difficulty at all to
<strong>C++</strong>'s template mechanism. Actually, having available a generic type
(<em>Context</em>) together with several concrete instantiations of that
generic type is a mere text-book argument for using templates.
<p>
<a name="l385"></a>
<h3>20.7.1: Local context structs</h3>
    <a name="concrete/context"></a>When a function is called, the context in which it is called is made known to
the function by providing the function with a parameter list. When the
function is called, these parameters are initialized by the function's
arguments. For example, a function <code>show()</code> may expect two arguments: an
<code>ostream &amp;</code> into which the information is inserted and an object which will
be inserted into the stream. For example:
        <pre>
    void State::show(ostream &amp;out, Item const &amp;item)
    {
        out &lt;&lt; "Here is item " &lt;&lt; item.nr() &lt;&lt; ":\n" &lt;&lt;
                item &lt;&lt; endl;
    }
</pre>
    Functions clearly differ in their parameter lists: both the numbers and
types of their parameters vary.
<p>
A <a name="an2989"></a>
<em>local context struct</em> is used to standardize the parameter lists of
functions, for the benefit of template construction. In the above example, the
function <code>State::show()</code> uses a local context consisting of an <code>ostream &amp;</code>
and an <code>Item const &amp;</code>. This context never changes, and may very well be
offered through a <code>struct</code> defined as follows:
        <pre>
    struct ShowContext
    {
        ostream &amp;out;
        Item const &amp;item;
    };
</pre>
    Note that this <code>struct</code> mimics <code>State::show()</code>'s parameter list. Since
it is directly connected to the function <code>State::show()</code> it is best defined
in the class <code>State</code>, offering the function <code>State::show()</code>. Once we have
defined this <code>struct</code>, <code>State::show()</code>'s implementation is modified so
that it now expects a <code>ShowContext &amp;</code>:
        <pre>
    void State::show(ShowContext &amp;context)
    {
        context.out &lt;&lt; "Here is item " &lt;&lt; context.item.nr() &lt;&lt; ":\n" &lt;&lt;
                context.item &lt;&lt; endl;
    }
</pre>
    (Alternatively, an overloaded <code>State::show(ShowContext &amp;context)</code>
could be defined, calling the original <code>show()</code> member).
<p>
Using a local context <code>struct</code> any parameter list (except those of
        <a name="an2990"></a>
variadic functions) can be standardized to a parameter list
consisting of a single element. Now that we have a single parameter to specify
any local context we're ready for the `templatization' of
    <a name="an2991"></a>
function object wrapper classes.
<p>
<a name="l386"></a>
<h3>20.7.2: Member functions called from function objects</h3>
    <a name="concrete/members"></a>    The member function called by function objects is the function
        <a name="an2992"></a>
<code>operator()()</code>, which may be defined as a function having various
parameters. In the context of generic algorithms, these parameters are usually
one or two elements, representing the data to which the algorithm's iterators
point. Unfortunately from the point of view of the template class constructor,
it is not known beforehand whether these data elements are objects, primitive
types, or pointers. Let's assume that we would like to create a function object
changing all letters in <code>string</code> objects into capital letters. In that case
our <code>operator()()</code> function may receive a <code>string &amp;</code> (e.g., when iterating
over the elements of a <code>vector&lt;string&gt;</code>), but our <code>operator()()</code> function
may also receive a <code>string *</code> (e.g., when iterating over the elements of a
<code>vector&lt;string *&gt;</code>). Other parameter types can be conceived of as well.
<p>
So, how can we define a generic function that can be called from
<code>operator()()</code> if we don't know (when defining the template) whether we
should call using <code>.*</code> or <code>-&gt;*</code>? The issue whether to call a member
function using a pointer to member in combination with an object or a pointer
to object does not have to be solved by the template. Instead it can be
handled by the class itself, if the class provides an appropriate <em>static</em>
member.
<p>
An additional advantage of using a static function is that the static
members do not have <code>const</code> attributes. Consequently, no ambiguity can arise
when calling a static member function from within a function object's
<code>operator()()</code>.
<p>
Generic algorithms, however, differ in their using of the function
object's <code>operator()()</code>'s return value. As will be illustrated in the next
section, the return type of called functions may also be parameterized.
<p>
<a name="WRAPONE"></a><a name="l387"></a>
<h3>20.7.3: The configurable, single argument function object template</h3>
        <a name="concrete/unary"></a>As an introductory example, let's assume we have a class <code>Strings</code> holding a
<code>vector&lt;string&gt; d_vs</code> data member. We would like to change all
letter-characters in the strings stored in <code>d_vs</code> into upper case
characters, and we would like to insert the original and modified strings
into a configurable <code>ostream</code> object.  To accomplish this, our class offers
a member <code>uppercase(ostream &amp;out)</code>.
<p>
We would like to use the  <code>for_each()</code> generic
algorithm. This algorithm may be given a function's address, or it may be
given a function object. Clearly, since we have a local context (the
configurable <code>ostream</code> object), the function object is required
here. Therefore, the following support class is constructed:
        <pre>
    class Support
    {
        std::ostream &amp;d_out;

        public:
            Support(std::ostream &amp;out);
            void operator()(std::string &amp;str) const;
    };

    inline Support::Support(std::ostream &amp;out)
    :
        d_out(out)
    {}

    inline void Support::operator()(std::string &amp;str) const
    {
        d_out &lt;&lt; str &lt;&lt; " ";
        transform(str.begin(), str.end(), str.begin(), toupper);
        d_out &lt;&lt; str &lt;&lt; std::endl;
    }
</pre>
An anonymous <code>Support</code> class object may now be used in the implementation of
the class <code>Strings</code>. Here is an example of its definition and use:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    #include &lt;vector&gt;
    #include &lt;algorithm&gt;

    #include "support.h"

    class Strings
    {
        std::vector&lt;std::string&gt; d_vs;

        public:
            void uppercase(std::ostream &amp;out);
    };

    void Strings::uppercase(std::ostream &amp;out)
    {
        for_each(d_vs.begin(), d_vs.end(), Support(out));
    }

    using namespace std;

    int main()
    {
        Strings s;

        s.uppercase(cout);
    }
</pre>
<p>
To `templatize' the <code>Support</code> class, using the considerations discussed
previously, we perform the following steps:
    <ul>
    <li> The local context will be put in a <code>struct</code>, which is then passed
to the template's constructor, so <code>Context</code> becomes one of the template type
parameters.
    <li> The implementation of the template's <code>operator()()</code> is
standardized. In the template it will call a function, receiving the
<code>operator()()</code>'s argument (which also becomes a template parameter) and a
reference to the context as its arguments. The address of the function to call
may be stored in a local variable of the template function object. In the
<code>Support</code> class, <code>operator()()</code> uses a <code>void</code> return type. This type is
often the required type, but when defining predicates it may be a
<code>bool</code>. Therefore, the return type of the template's <code>operator()()</code> (and
thus the return type of the called function) is made configurable as well,
offering a default type <code>void</code> for convenience. Thus, we get the following
definition of the variable holding the address of the function to call:
        <pre>
    ReturnType (*d_fun)(Type &amp;argument, Context &amp;context);
</pre>
    and the template's <code>operator()()</code> implementation (passing it another
template data member: <code>Context &amp;d_context</code>) becomes:
        <pre>
    template&lt;typename Type, typename Context, typename ReturnType&gt;
    ReturnType Wrap1&lt;Type, Context, ReturnType&gt;::operator()(
                                                Type &amp;param) const
    {
        return (*d_fun)(param, d_context);
    }
</pre>
    <li> The template's constructor is given two parameters: a function
address and a reference to the local context <code>struct</code>. Coining the classname
<code>Wrap1</code> (for unary (1) function object wrapper), its implementation
becomes:
        <pre>
    template&lt;typename Type, typename Context, typename ReturnType&gt;
    Wrap1&lt;Type, Context, ReturnType&gt;::
    Wrap1(ReturnType (*fun)(Type &amp;, Context &amp;), Context &amp;context)
    :
        d_fun(fun),
        d_context(context)
    {}
</pre>
    </ul>
    Now we're almost ready to construct the full template class <code>Wrap1</code>. Two
additional situations need further consideration:
    <ul>
    <li> Arguments passed to the template's <code>operator()()</code> member may be of
various kinds: values, modifiable references, immutable (<code>const</code>)
references, pointers to modifiable entities or pointers to immutable
entities. The template should offer facilities to use all these different
argument types.
    <li> Algorithms defined in the standard template library, notably those
requiring <em>predicate</em> function objects (e.g., <code>find_if()</code>), assume that
these objects define internal types, named <a name="an2993"></a>
<code>result_type</code> for its
<code>operator()()</code> member, and <a name="an2994"></a>
<code>argument_type</code> for its data type. With binary
predicate function objects (see section <a href="cplusplus20.html#WRAPTWO">20.7.4</a>) <a name="an2995"></a>
<code>first_argument_type</code>
and <a name="an2996"></a>
<code>second_argument_type</code> for the respective types of its
<code>operator()()</code>'s arguments are expected. Moreover, these types must be
`plain' type names, no pointers nor references.
    </ul>
    Various parameter types of the template's <code>operator()()</code> function may be
handled by overloaded versions of both the template constructor and its
<code>operator()()</code> member, defining four implementations handling <code>Type const</code>
references and <code>Type const</code> pointers. For each of these situations a
function pointer to a corresponding function, called by the template's
<code>operator()()</code> must be defined as well. Since in each instantiation of the
template only <em>one</em> type of the overloaded functions (constructor and
associated <code>operator()()</code>) will be used, a <code>union</code> can be defined
accomodating the pointers to the various (i.e., four) types of functions that
may be passed to the template's constructor. This <code>union</code> may be
    <a name="an2997"></a>
 <em>anonymous</em>, as only its fields will be used. Note
that <em>value</em> arguments may be handled by <code>Type const &amp;</code> parameters: no
additional overloaded version is required to handle value-type arguments.
<p>
The internal types expected by some of the STL functions can simply be
made available by defining internal <code>typedef</code>s. Since the various types of
arguments (<code>const</code>, pointers, references) are handled by the template's
overloaded constructors and member functions, the typedefs may simply set up
aliases for the template parameter types.
<p>
Here is the full implementation of the configurable, single argument
function object template:
        <pre>
    template &lt;typename Type, typename Context, typename ReturnType = void&gt;
    class Wrap1
    {
        union
        {
            Context *d_context;
            Context const *d_contextconst;
        };
        union
        {
            ReturnType (*d_ref)(Type &amp;, Context &amp;);
            ReturnType (*d_refPtr)(Type &amp;, Context *);
            ReturnType (*d_refCref)(Type &amp;, Context const &amp;);
            ReturnType (*d_refCptr)(Type &amp;, Context const *);

            ReturnType (*d_ptr)(Type *, Context &amp;);
            ReturnType (*d_ptr2)(Type *, Context *);
            ReturnType (*d_ptrCref)(Type *, Context const &amp;);
            ReturnType (*d_ptrCptr)(Type *, Context const *);

            ReturnType (*d_crefRef)(Type const &amp;, Context &amp;);
            ReturnType (*d_crefPtr)(Type const &amp;, Context *);
            ReturnType (*d_cref2)(Type const &amp;, Context const &amp;);
            ReturnType (*d_crefCptr)(Type const &amp;, Context const *);

            ReturnType (*d_cptrRef)(Type const *, Context &amp;);
            ReturnType (*d_cptrPtr)(Type const *, Context *);
            ReturnType (*d_cptrCref)(Type const *, Context const &amp;);
            ReturnType (*d_cptr2)(Type const *, Context const *);
        };

        public:
            typedef Type        argument_type;
            typedef ReturnType  result_type;


            // Type may be &amp;, *, const &amp;, and const *
            // Context may be &amp;, *, const &amp;. and const *
            // This allows for 16 combinations which are now all implemented
            // below

            Wrap1(ReturnType (*fun)(Type &amp;, Context &amp;), Context &amp;context);
            Wrap1(ReturnType (*fun)(Type &amp;, Context const &amp;),
                   Context const &amp;context);
            Wrap1(ReturnType (*fun)(Type const &amp;, Context &amp;),
                   Context &amp;context);
            Wrap1(ReturnType (*fun)(Type const &amp;, Context const &amp;),
                   Context const &amp;context);
            Wrap1(ReturnType (*fun)(Type *, Context &amp;),
                   Context &amp;context);
            Wrap1(ReturnType (*fun)(Type *, Context const &amp;),
                   Context const &amp;context);
            Wrap1(ReturnType (*fun)(Type const *, Context &amp;),
                   Context &amp;context);
            Wrap1(ReturnType (*fun)(Type const *, Context const &amp;),
                   Context const &amp;context);

            // The following additional constructors are identical to the
            // constructors listed above, but they accept a pointer to a
            // context in various forms.

            Wrap1(ReturnType (*fun)(Type &amp;, Context *), Context *context);
            Wrap1(ReturnType (*fun)(Type &amp;, Context const *),
                   Context const *context);
            Wrap1(ReturnType (*fun)(Type const &amp;, Context *),
                   Context *context);
            Wrap1(ReturnType (*fun)(Type const &amp;, Context const *),
                   Context const *context);
            Wrap1(ReturnType (*fun)(Type *, Context *), Context *context);
            Wrap1(ReturnType (*fun)(Type *, Context const *),
                   Context const *context);
            Wrap1(ReturnType (*fun)(Type const *, Context *),
                   Context *context);
            Wrap1(ReturnType (*fun)(Type const *, Context const *),
                   Context const *context);

            ReturnType operator()(Type &amp;param) const;
            ReturnType operator()(Type const &amp;param) const;
            ReturnType operator()(Type *param) const;
            ReturnType operator()(Type const *param) const;
    };


template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type &amp;, Context &amp;), Context &amp;context)
:
    d_context(&amp;context),
    d_ref(fun)
{}
                                    // reference Wrap1::const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type &amp;, Context const &amp;),
                Context const &amp;context)
:
    d_contextconst(&amp;context),
    d_refCref(fun)
{}

                                    // const reference
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const &amp;, Context &amp;),
                Context &amp;context)
:
    d_context(&amp;context),
    d_crefRef(fun)
{}
                                    // const reference const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const &amp;, Context const &amp;),
                Context const &amp;context)
:
    d_contextconst(&amp;context),
    d_cref2(fun)
{}

                                    // pointer
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type *, Context &amp;),
       Context &amp;context)
:
    d_context(&amp;context),
    d_ptr(fun)
{}
                                    // pointer const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type *, Context const &amp;),
                Context const &amp;context)
:
    d_contextconst(&amp;context),
    d_ptrCref(fun)
{}

                                    // const pointer
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const *, Context &amp;),
                Context &amp;context)
:
    d_context(&amp;context),
    d_cptrRef(fun)
{}
                                    // const pointer const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const *, Context const &amp;),
                Context const &amp;context)
:
    d_contextconst(&amp;context),
    d_cptrCref(fun)
{}

                                    // reference
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type &amp;, Context *), Context *context)
:
    d_context(context),
    d_refPtr(fun)
{}
                                    // reference const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type &amp;, Context const *),
                Context const *context)
:
    d_contextconst(context),
    d_refCptr(fun)
{}

                                    // const reference
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const &amp;, Context *), Context *context)
:
    d_context(context),
    d_crefPtr(fun)
{}
                                    // const reference const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const &amp;, Context const *),
                Context const *context)
:
    d_contextconst(context),
    d_crefCptr(fun)
{}

                                    // pointer
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type *, Context *), Context *context)
:
    d_context(context),
    d_ptr2(fun)
{}
                                    // pointer const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type *, Context const *),
                Context const *context)
:
    d_contextconst(context),
    d_ptrCptr(fun)
{}
                                    // const pointer
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const *, Context *), Context *context)
:
    d_context(context),
    d_cptrPtr(fun)
{}
                                    // const pointer const
template &lt;typename Type, typename Context, typename ReturnType&gt;
Wrap1&lt;Type, Context, ReturnType&gt;::Wrap1(
                ReturnType (*fun)(Type const *, Context const *),
                Context const *context)
:
    d_contextconst(context),
    d_cptr2(fun)
{}

template &lt;typename Type, typename Context, typename ReturnType&gt;
ReturnType Wrap1&lt;Type, Context, ReturnType&gt;::operator()(Type &amp;param) const
{
    return (*d_ref)(param, *d_context);
}

template &lt;typename Type, typename Context, typename ReturnType&gt;
ReturnType
        Wrap1&lt;Type, Context, ReturnType&gt;::operator()(Type const &amp;param) const
{
    return (*d_crefRef)(param, *d_context);
}

template &lt;typename Type, typename Context, typename ReturnType&gt;
ReturnType Wrap1&lt;Type, Context, ReturnType&gt;::operator()(Type *param) const
{
    return (*d_ref)(*param, *d_context);
}

template &lt;typename Type, typename Context, typename ReturnType&gt;
ReturnType
        Wrap1&lt;Type, Context, ReturnType&gt;::operator()(Type const *param) const
{
    return (*d_crefRef)(*param, *d_context);
}
</pre>
<p>
To use this template, the original dedicated implementation of
<code>Support::operator()()</code> is now defined in a static member function of the
class <code>String</code>, also defining the required local context struct. Here is
the new implementation of the class <code>Strings</code>, using the template <code>Wrap1</code>:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    #include &lt;vector&gt;
    #include &lt;algorithm&gt;

    #include "wrap1.h"

    class Strings
    {
        std::vector&lt;std::string&gt; d_vs;

        struct Context
        {
            std::ostream &amp;out;
        };

        public:
            void uppercase(std::ostream &amp;out);

        private:
            static void xform(std::string &amp;str, Context &amp;context);
    };

    void Strings::uppercase(std::ostream &amp;out)
    {
        Context context = {out};
        for_each(d_vs.begin(), d_vs.end(),
            Wrap1&lt;std::string, Context&gt;(&amp;xform, context));
    }

    void Strings::xform(std::string &amp;str, Context &amp;context)
    {
        context.out &lt;&lt; str &lt;&lt; " ";
        transform(str.begin(), str.end(), str.begin(), toupper);
        context.out &lt;&lt; str &lt;&lt; std::endl;
    }

    using namespace std;

    int main()
    {
        Strings s;

        s.uppercase(cout);
    }
</pre>
<p>
To illustrate the use of the <code>ReturnType</code> template parameter, let's
assume that the transformations are only required up to the first empty
string. In this case, the <code>find_if</code> generic algorithm comes in handy, since
it stops once a predicate returns <code>true</code>. The <code>xform()</code> function should
return a <code>bool</code> value, and the <code>uppercase()</code> implementation specifies an
explicit type (<code>bool</code>) for the <code>ReturnType</code> template parameter:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    #include &lt;vector&gt;
    #include &lt;algorithm&gt;

    #include "wrap1.h"

    class Strings
    {
        std::vector&lt;std::string&gt; d_vs;

        struct Context
        {
            std::ostream &amp;out;
        };

        public:
            void uppercase(std::ostream &amp;out);

        private:
            static bool xform(std::string &amp;str, Context &amp;context);
    };

    void Strings::uppercase(std::ostream &amp;out)
    {
        Context context = {out};
        find_if(d_vs.begin(), d_vs.end(),
            Wrap1&lt;std::string, Context, bool&gt;(&amp;xform, context));
    }

    bool Strings::xform(std::string &amp;str, Context &amp;context)
    {
        context.out &lt;&lt; str &lt;&lt; " ";
        transform(str.begin(), str.end(), str.begin(), toupper);
        context.out &lt;&lt; str &lt;&lt; std::endl;

        return str.empty();
    }

    using namespace std;

    int main()
    {
        Strings s;

        s.uppercase(cout);
    }
</pre>
    Note that only the class <code>Strings</code> needed to be modified. The <code>Wrap1</code>
template could be used to create both the plain, <code>void</code> returning function
object and the unary predicate.
<p>
A final note: sometimes no context is required at all, but the approach
taken with the <code>Wrap1</code> template class may be considered useful. In those
cases, either a dummy context may be defined, or a alternate wrapper class not
using a context may be defined. Personally, I've done the latter.
<p>
<a name="WRAPTWO"></a><a name="l388"></a>
<h3>20.7.4: The configurable, two argument function object template</h3>
    <a name="concrete/binary"></a>    Having constructed the unary template wrapper, the construction of the
binary template wrapper should offer no surprises. The function object's
<code>operator()()</code> is now called with two, rather than one argument. Coining the
classname <code>Wrap2</code>, it's implementation is almost identical to <code>Wrap1</code>'s
implementation. It's full implementation consists of slightly over 1100 lines,
due to the various combinations of <code>const</code> and pointer or reference
parameters and can be found in the 
        <a href="http://bobcat.sourceforge.net">Bobcat library</a>.
        <a name="an2998"></a>
<a name="an2999"></a>
. An excerpt from
that class, showing the use of <code>const *</code> parameters, is:
        <pre>
template &lt;typename Type1, typename Type2,
          typename Context, typename ReturnType = void&gt;
class Wrap2c
{
    union
    {
        Context *d_context;
        Context const *d_contextconst;
    };
    union
    {
        // from right to left the following is varied:
        //          references, pointers,
        //          const references, const pointers
        //  This makes for 4 variations on parameter 3,
        //      x 4 variations on parameter 2
        //      x 4 variations on parameter 1 = 64 variations

        // 3 sets of 16 variations not shown
        // set 4: 16  variations for Type1 const *:
            // 12 variations not shown.

        ReturnType (*d_cptr2ref)(Type1 const *, Type2 const *,
                                                        Context &amp;);
        ReturnType (*d_cptr2ptr)(Type1 const *, Type2 const *,
                                                        Context *);
        ReturnType (*d_cptr2cref)(Type1 const *, Type2 const *,
                                                        Context const &amp;);
        ReturnType (*d_cptr3)(Type1 const *, Type2 const *,
                                                        Context const *);
    };

    public:
        typedef Type1       first_argument_type;
        typedef Type2       second_argument_type;
        typedef ReturnType  result_type;

        // Type1 may be &amp;, const &amp;, * and const *
        // Type2 may be &amp;, const &amp;, * and const *
        // Context may be &amp;, const &amp;. * and const *
        // This allows for 64 combinations

    // Three blocks of 16 constructors not shown

    // Fourth block of 16 constructors: Type1 const *
        // Type 1: const *, Type2: &amp;            - not shown
        // Type 1: const *, Type2: *            - not shown
        // Type 1: const *, Type2: const &amp;      - not shown

        // Type 1: const *, Type2: const *
        Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context &amp;),
               Context &amp;context);
        Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context *),
               Context *context);
        Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *,
                                 Context const &amp;), Context const &amp;context);
        Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *,
                                 Context const *), Context const *context);

    // Member functions: 16, for ref, ptr, const ref, const ptr,
    //                       and two parameters per function
    // Type 1: ref          - not shown
    // Type 1: ptr          - not shown
    // Type 2: const ref    - not shown

    // Type 2: const ptr
        // ...
        ReturnType operator()(Type1 const *param1, Type2 const *param2) const;
};

// Fourth block of 16 constructors: Type1 const *

    // Type 1: const *, Type2: const *

    template&lt;typename Type1, typename Type2, typename Context,
             typename ReturnType&gt;
    Wrap2c&lt;Type1, Type2, Context, ReturnType&gt;::
    Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context &amp;),
           Context &amp;context)
    :
        d_context(&amp;context),
        d_cptr2ref(fun)
    {}

    template&lt;typename Type1, typename Type2, typename Context,
             typename ReturnType&gt;
    Wrap2c&lt;Type1, Type2, Context, ReturnType&gt;::
    Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context *),
           Context *context)
    :
        d_context(context),
        d_cptr2ptr(fun)
    {}

    template&lt;typename Type1, typename Type2, typename Context,
             typename ReturnType&gt;
    Wrap2c&lt;Type1, Type2, Context, ReturnType&gt;::
    Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context const &amp;),
           Context const &amp;context)
    :
        d_contextconst(&amp;context),
        d_cptr2cref(fun)
    {}

    template&lt;typename Type1, typename Type2, typename Context,
             typename ReturnType&gt;
    Wrap2c&lt;Type1, Type2, Context, ReturnType&gt;::
    Wrap2c(ReturnType (*fun)(Type1 const *, Type2 const *, Context const *),
           Context const *context)
    :
        d_contextconst(context),
        d_cptr3(fun)
    {}

// Member functions: 16, for ref, ptr, const ref, const ptr,
//                       and two parameters per function
// ...

// Type 2: const ptr
    // ...

    template&lt;typename Type1, typename Type2, typename Context,
             typename ReturnType&gt;
    ReturnType Wrap2c&lt;Type1, Type2, Context, ReturnType&gt;::
    operator()(Type1 const *param1, Type2 const *param2) const
    {
        return (*d_cref2ref)(*param1, *param2, *d_context);
    }
</pre>
    As with the unary template wrapper (see section <a href="cplusplus20.html#WRAPONE">20.7.3</a>), an
additional class may be defined that does not require a local context.
<p>
<a name="BisonAndFlex"></a><a name="l389"></a>
<h2>20.8: Using `bisonc++' and `flex'</h2>
<a name="concrete/bisonflex"></a>    The example discussed in this section digs into the peculiarities of using
a <a name="an3000"></a>
parser- and <a name="an3001"></a>
scanner generator generating <strong>C++</strong> sources. Once the
input for a program exceeds a certain level of complexity, it's advantageous
to use a scanner- and parser-generator to create the code which does the
actual input recognition.
<p>
The current example assumes that the reader knows how to use the
    <a name="an3002"></a>
scanner generator <a name="an3003"></a>
<code>flex</code> and the <a name="an3004"></a>
parser generator <a name="an3005"></a>
<code>bison</code>. Both
<code>bison</code> and <code>flex</code> are well documented elsewhere. The original
predecessors of <code>bison</code> and <code>flex</code>, called <a name="an3006"></a>
<code>yacc</code> and <a name="an3007"></a>
<code>lex</code> are
described in several books, e.g. in
    <a name="an3008"></a>

    O'Reilly's book <a href="http://www.oreilly.com/catalog/lex">`lex &amp; yacc'</a>.
<p>
However, scanner- and parser generators are also (and maybe even more
commonly, nowadays) available as free software. Both <code>bison</code> and <code>flex</code>
are usually part of software distributions or they can be obtained from
    <a name="an3009"></a>

    <a target=_top href="ftp://prep.ai.mit.edu/pub/non-gnu">ftp://prep.ai.mit.edu/pub/non-gnu</a>. <code>Flex</code> creates a <code>C++</code> class
when <a name="an3010"></a>
<code>%option c++</code> is specified.
<p>
For parser generators the program <a name="an3011"></a>
<code>bison</code> is available. Back in the early
90's <em>Alain Coetmeur</em> (<a href="mailto:coetmeur@icdc.fr">coetmeur@icdc.fr</a>)
created a <strong>C++</strong> variant (<a name="an3012"></a>
<code>bison++</code>) creating a parser class. Although
<code>bison++</code> program produces code that can be used in <strong>C++</strong> programs it also
shows many characteristics that are more appropriate in a <strong>C</strong> context than
in a <strong>C++</strong> context. In January 2005 I rewrote parts of Alain's <code>bison++</code>
program, resulting in the original version of the program <a name="an3013"></a>
<strong>bisonc++</strong>. Then,
in May 2005 a complete rewrite of the <code>bisonc++</code> parser gegerator was
completed, which is available on the Internet having version numbers 0.98 and
beyond. <code>Bisonc++</code> can be downloaded from
    <a target=_top href="http://bisoncpp.sourceforge.net/">http://bisoncpp.sourceforge.net/</a>, where it is available as source
archive and as binary (i386) <a href="http://www.debian.org">Debian</a> binary package
(including <code>bisonc++</code>'s documentation). <code>Bisonc++</code> creates a cleaner
parser class setup than <code>bison++</code>. In particular, it derives the parser
class from a base-class, containing the parser's token- and type-definitions
as well as all member functions which should not be (re)defined by the
programmer. Most of these members might also be defined directly in the parser
class. Because of this approach, the resulting parser class is very small,
declaring only members that are actually defined by the programmer (as well as
some other members, generated by <code>bisonc++</code> itself, implementing the
parser's <a name="an3014"></a>
<code>parse()</code> member). Actually, <code>parse()</code> is initially the <em>only</em>
public member of <code>bisonc++</code>'s generated parser class. Remaining members are
private. The only member which is <em>not</em> implemented by default is <code>lex()</code>,
producing the next lexical token. When the directive <code>%scanner</code> (see section
<a href="cplusplus20.html#BISONDEF">20.8.2.1</a>) is used, <code>bisonc++</code> will generate a standard implementation
for this member; otherwise it must be implemented by the programmer.
<p>
In this section of the Annotations we will focus on <code>bisonc++</code> as our
<a name="an3015"></a>
<em>parser generator</em>.
<p>
Using <code>flex</code> and <code>bisonc++</code> <code>class</code>-based scanners and parsers can be
generated. The advantage of this approach is that the interface to the scanner
and the parser tends to become cleaner than without using the <code>class</code>
interface. Furthermore, classes allow us to get rid of most if not all global
variables, making it easy to use multiple parsers in one program.
<p>
Below two examples are elaborated. The first example only uses <code>flex</code>. The
scanner it generates monitors the production of a file from several
parts. This example focuses on the lexical scanner, and on switching files
while churning through the information. The second example uses both <code>flex</code>
and <code>bisonc++</code> to generate a scanner and a parser transforming standard
arithmetic expressions to their postfix notations, commonly used in
code generated by compilers and in <code>HP</code>-calculators.  In the second example
the emphasis is mainly on <code>bisonc++</code> and on composing a scanner object
inside a generated parser.
<p>
<a name="Flexpp"></a><a name="l390"></a>
<h3>20.8.1: Using `flex' to create a scanner</h3>
    <a name="concrete/usingflex"></a>    The lexical scanner developed in this section is used to monitor the
production of a file from several subfiles. The setup is as follows: the
<a name="an3016"></a>
input-language knows of an <a name="an3017"></a>
<code>#include</code> directive, followed by a text
string specifying the file (path) which should be included at the location of
the <code>#include</code>.
<p>
In order to avoid complexities irrelevant to the current example, the format
of the <code>#include</code> statement is restricted to the form
        <a name="an3018"></a>
<code>#include &lt;filepath&gt;</code>.  The file specified between the pointed
brackets should be available at the location indicated by <code>filepath</code>. If the
file is not available, the program terminates after issuing an error message.
<p>
The program is started with one or two filename arguments. If the program is
started with just one filename argument, the output is written to the
    <a name="an3019"></a>
standard output stream <code>cout</code>. Otherwise, the output is written to
the stream whose name is given as the program's second argument.
<p>
The program defines a maximum <a name="an3020"></a>
nesting depth. Once this maximum is exceeded,
the program terminates after issuing an error message. In that case, the
filename <a name="an3021"></a>
stack indicating where which file was included is printed.
<p>
One additional feature is that (standard <strong>C++</strong>) <a name="an3022"></a>
comment-lines are
ignored. So, <code>include</code> directives in comment-lines are ignored too.
<p>
The program is created along the following steps:
    <ul>
    <li> First, the file <code>lexer</code> is constructed, containing the
input-language specifications.
    <li> From the specifications in <code>lexer</code> the requirements for the
<code>class Scanner</code> evolve. The <code>Scanner</code> class is a <a name="an3023"></a>
wrapper around the
class <a name="an3024"></a>
<code>yyFlexLexer</code> generated by <a name="an3025"></a>
<code>flex</code>. The requirements result in the
<a name="an3026"></a>
interface specification for the class <code>Scanner</code>.
    <li> Next, <code>main()</code> is constructed. A <code>Scanner</code> object
is created  inspecting the <a name="an3027"></a>
command-line arguments. If successful,
the scanner's member <code>yylex()</code> is called to construct the
output file.
    <li> Now that  the global setup of the program has been specified,
the member functions of the various classes are constructed.
    <li> Finally, the program is compiled and linked.
    </ul>
<p>
<a name="l391"></a>
<strong>20.8.1.1: The derived class `Scanner'</strong>
        <a name="concrete/lexer"></a>    The code associated with the <a name="an3028"></a>
regular expression rules is located inside
the class <code>yyFlexLexer</code>. However, we would of course want to use the
derived class's members in this code. This causes a little problem: how does a
base-class member know about members of classes derived from it?
<p>
Fortunately, <a name="an3029"></a>
inheritance helps us to realize this. In the specification of
the class <code>yyFlexLexer()</code>, we notice that the function <a name="an3030"></a>
<code>yylex()</code> is a
<a name="an3031"></a>
<em>virtual</em> function. The header file <code>FlexLexer.h</code> declares the
<code>virtual</code> member <code>int yylex()</code>:
        <pre>
    class yyFlexLexer: public FlexLexer
    {
        public:
            yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 );

            virtual ~yyFlexLexer();

            void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
            struct yy_buffer_state* yy_create_buffer( istream* s, int size );
            void yy_delete_buffer( struct yy_buffer_state* b );
            void yyrestart( istream* s );

            virtual int yylex();

            virtual void switch_streams( istream* new_in, ostream* new_out );
    };
</pre>
    As this function is a virtual function it can be overridden in a
<em>derived</em> class. In that case the overridden function will be called from
its <a name="an3032"></a>
base class (i.e., <code>yyFlexLexer</code>) code. Since the derived class's
<code>yylex()</code> is called, it will now have access to the members of the derived
class, and also to the public and protected members of its base class.
<p>
By default, the context in which the generated scanner is placed is the
function <a name="an3033"></a>
<code>yyFlexLexer::yylex()</code>. This context changes if we use a derived
class, e.g., <code>Scanner</code>. To derive <code>Scanner</code> from <code>yyFlexLexer</code>,
generated by <code>flex</code>, do as follows:
    <ul>
    <li> The function <code>yylex()</code> must be declared in the derived class
<code>Scanner</code>.
    <li> <em>Options</em> (see below) are used to inform <code>flex</code> about the derived
class's name.
    </ul>
<p>
Looking at the regular expressions themselves, notice that we need
rules to  recognize comment, <code>#include</code> directives,
    <a name="an3034"></a>

    and all remaining characters.  This is all fairly standard practice. When
an <code>#include</code> directive is detected, the directive is parsed by the
scanner. This too is <a name="an3035"></a>
common practice. Here is what our lexical scanner will
do:
    <ul>
    <li> As usual, <a name="an3036"></a>
 preprocessor directives are not
analyzed by a <a name="an3037"></a>
parser, but by the <a name="an3038"></a>
lexical scanner;
    <li> The scanner uses a <a name="an3039"></a>
mini scanner to extract the filename from the
directive, throwing a <code>Scanner::Error</code> value (<code>invalidInclude</code>) if this
fails;
    <li> If the filename could be extracted, it is stored in <code>nextSource</code>;
    <li> When the <code>#include</code> directive has been processed,
<code>pushSource()</code> is called to perform the switch to another file;
    <li> When the end of the file (<code>EOF</code>) is reached, the derived class's
member function <code>popSource()</code> is called, popping the previously
pushed file and returning <a name="an3040"></a>
<code>true</code>;
    <li> Once the file-stack is empty, <code>popSource()</code> returns <a name="an3041"></a>
<code>false</code>,
resulting in calling <code>yyterminate()</code>, terminating the scanner.
    </ul>
<p>
The <a name="an3042"></a>
lexical scanner specification file is organized similarly as the
one used for <code>flex</code> in <strong>C</strong> contexts. However, for <strong>C++</strong> contexts,
<code>flex</code> may create a class (<a name="an3043"></a>
<code>yyFlexLexer</code>) from which another class (e.g.,
<code>Scanner</code>) can be
        <a name="an3044"></a>

derived. The <a name="an3045"></a>
flex specification file itself has three sections:
    <ul>
    <li> The lexer specification file's first section is a <strong>C++</strong>
<a name="an3046"></a>
<em>preamble</em>, containing code which can be used in the code defining the
<a name="an3047"></a>
actions to be performed once a regular expression is matched. In the
current setup, where each class has its own <em>internal header file</em>, the
internal header file includes the file <code>scanner.h</code>, in turn including
<a name="an3048"></a>
<code>FlexLexer.h</code>, which is part of the <code>flex</code> distribution.
<p>
However, due to the complex setup of this latter file, it should not be
read again by the code generated by <code>flex</code>. So, we now have the
following situation:
        <ul>
        <li> First we look at the lexer specification file. It contains a
preamble including <code>scanner.ih</code>, since this declares, via <code>scanner.h</code> the
class <code>Scanner</code>, so that we're able to call <code>Scanner</code>'s members from the
code associated with the regular expressions defined in the lexer
specification file.
        <li> In <code>scanner.h</code>, defining <code>class Scanner</code>, the header file
<code>FlexLexer.h</code>, declaring <code>Scanner</code>'s base class, <em>must</em> have been read
by the compiler before the class <code>Scanner</code> itself is defined.
        <li> Code generated by <code>flex</code> already includes <code>FlexLexer.h</code>,
and as mentioned, <code>FlexLexer.h</code> may not be read again. However, <code>flex</code> will
also insert the specification file's preamble into the code it generates.
        <li> Since this preamble includes <code>scanner.ih</code>, and so
<code>scanner.h</code>, and so <code>FlexLexer.h</code>, we now <em>do</em> include <code>FlexLexer.h</code>
twice in code generated by <code>flex</code>. This must be prevented.
        </ul>
        To prevent multiple inclusions of <code>FlexLexer.h</code> the following is
suggested:
        <ul>
        <li> Although <code>scanner.ih</code> includes <code>scanner.h</code>, <code>scanner.h</code>
itself is modified such that it includes <code>FlexLexer.h</code>, <em>unless</em> the <strong>C</strong>
preprocesser variable <a name="an3049"></a>
<code>_SKIP_FLEXLEXER_</code> is defined.
        <li> In <code>flex</code>' specification file <code>_SKIP_FLEXLEXER_</code> is defined
just prior to including <code>scanner.ih</code>.
        </ul>
        Using this scheme, code generated by <code>flex</code> will now re-include
<code>FlexLexer.h</code>. At the same time, compiling <code>Scanner</code>'s members proceeds
independently of the lexer specification file's preamble, so here
<code>FlexLexer.h</code> is properly included too. Here is the specification files'
preamble:
                    <pre>
%{
    #define _SKIP_YYFLEXLEXER_
    #include "scanner.ih"
%}
</pre>
<p>
<li> The specification file's second section is a <code>flex</code>
        <a name="an3050"></a>
<em>symbol area</em>, used to define symbols, like a <a name="an3051"></a>
mini scanner, or
<a name="an3052"></a>
<em>options</em>. The following options are suggested:
        <ul>
        <li> <a name="an3053"></a>
<code>%option 8bit</code>: this allows the generated lexical scanner to
read 8-bit characters (rather than 7-bit, which is the default).
        <li> <a name="an3054"></a>
<code>%option c++</code>: this results in <code>flex</code> generating <strong>C++</strong>
code.
        <li> <a name="an3055"></a>
<code>%option debug</code>: this will include <em>debugging</em>
        <a name="an3056"></a>
 code into the code generated by
<code>flex</code>. Calling the member function <a name="an3057"></a>
<code>set_debug(true)</code> will activate this
debugging code run-time. When activated, information about which rules are
matched is written to the standard error stream. To suppress the execution of
debug code the member function <code>set_debug(false)</code> may be called.
        <li> <a name="an3058"></a>
<code>%option noyywrap</code>: when the scanner reaches the end of file,
it will (by default) call a function <code>yywrap()</code> which may perform the switch
to another file to be processed. Since there exist alternatives which render
this function superfluous (see below), it is suggested to specify this option
as well.
        <li> <a name="an3059"></a>
<code>%option outfile</code><code>="yylex.cc"</code>: this defines <code>yylex.cc</code> as
the name of the generated <strong>C++</strong> source file.
        <li> <a name="an3060"></a>
<code>%option warn</code>: this option is strongly suggested by the
<code>flex</code> documentation, so it's mentioned here as well. See <code>flex</code>'
documentation for details.
        <li> <a name="an3061"></a>
<code>%option yyclass</code><code>="Scanner"</code>: this defines <code>Scanner</code> as
the name of the class derived from <code>yyFlexLexer</code>.
        <li>  <a name="an3062"></a>
<code>%option yylineno</code>: this option causes the
lexical scanner to keep track of the <a name="an3063"></a>
line numbers of the files it is
scanning. When processing nested files, the variable <code>yylineno</code> is not
automatically reset to the last line number of a file, when returning
to a partially processed file. In those cases, <code>yylineno</code> will explicitly
have to be reset to a former value. If specified, the current line number is
returned by the public member <a name="an3064"></a>
<code>lineno()</code>, returning an <code>int</code>.
        </ul>
    Here is the specification files' symbol area:
                    <pre>
%option yyclass="Scanner" outfile="yylex.cc" c++ 8bit warn noyywrap yylineno
%option debug

%x      comment
%x      include

eolnComment     "//".*
anyChar         .|\n
</pre>
<p>
<li> The specification file's third section is a <a name="an3065"></a>
<em>rules section</em>, in
which the regular expressions and their associated actions are defined.
    In the example developed here,  the lexer should
    <a name="an3066"></a>
copy information from the <a name="an3067"></a>
<code>istream</code> <code>*yyin</code> <a name="an3068"></a>
 to the
    <a name="an3069"></a>
 <a name="an3070"></a>
<code>ostream</code> <code>*yyout</code>. For this  the predefined macro
    <a name="an3071"></a>
<code>ECHO</code> can be used.  Here is the specification files' symbol area:
                    <pre>
%%
    /*
        The comment-rules: comment lines are ignored.
    */
{eolnComment}
"/*"                    BEGIN comment;
&lt;comment&gt;{anyChar}
&lt;comment&gt;"*/"           BEGIN INITIAL;

    /*
        File switching: #include &lt;filepath&gt;
    */
#include[ \t]+"&lt;"       BEGIN include;
&lt;include&gt;[^ \t&gt;]+       d_nextSource = yytext;
&lt;include&gt;"&gt;"[ \t]*\n    {
                            BEGIN INITIAL;
                            pushSource(YY_CURRENT_BUFFER, YY_BUF_SIZE);
                        }
&lt;include&gt;{anyChar}      throw invalidInclude;

    /*
        The default rules: eating all the rest, echoing it to output
    */
{anyChar}               ECHO;

    /*
        The &lt;&lt;EOF&gt;&gt; rule: pop a pushed file, or terminate the lexer
    */
&lt;&lt;EOF&gt;&gt;                 {
                            if (!popSource(YY_CURRENT_BUFFER))
                                yyterminate();
                        }
%%
</pre>
<p>
</ul>
    Since the derived class's members may now access the information stored
within the lexical scanner itself (it can even access the information
<em>directly</em>, since the data members of <code>yyFlexLexer</code> are <a name="an3072"></a>
protected, and
thus accessible to derived classes), most processing can be left to the
derived class's member functions.  This results in a very clean setup of the
lexer specification file, requiring no or hardly any code in the <em>preamble</em>.
<p>
<a name="l392"></a>
<strong>20.8.1.2: Implementing `Scanner'</strong>
        <a name="concrete/scanner"></a>    The <code>class Scanner</code> is derived from the class <a name="an3073"></a>
<code>yyFlexLexer</code>, generated
by <a name="an3074"></a>
<code>flex</code>. The derived class has access to data controlled by the lexical
scanner. In particular, it has access to the following data members:
        <a name="an3075"></a>

    <ul>
    <li><a name="an3076"></a>
<code>char *yytext</code>, containing the <a name="an3077"></a>
 text
matched by a <a name="an3078"></a>
regular expression. Clients may access this information using
the scanner's <a name="an3079"></a>
<code>YYText()</code> member;
    <li><a name="an3080"></a>
<code>int yyleng</code>, the <a name="an3081"></a>
 length of the
text in <code>yytext</code>. Clients may access this value using the scanner's
<a name="an3082"></a>
<code>YYLeng()</code> member;
    <li><a name="an3083"></a>
<code>int yylineno</code>: the current <a name="an3084"></a>
line number. This
variable is only maintained if
        <code>%option yylineno</code> <a name="an3085"></a>
 is specified. Clients
may access this value using the scanner's <a name="an3086"></a>
<code>lineno()</code> member.
    </ul>
    Other members are available as well, but are used less often. Details can
be found in <a name="an3087"></a>
<code>FlexLexer.h</code>.
<p>
Objects of the <code>class Scanner</code> perform two tasks:
    <ul>
    <li> They push file information about the current file to a <a name="an3088"></a>
file stack;
    <li> They pop the last-pushed information from the stack once <code>EOF</code>
is detected in a file.
    </ul>
    Several member functions are used to accomplish these tasks. As they are
auxiliary to the scanner, they are <a name="an3089"></a>
private members.  In practice, develop
these private members once the need for them arises.  Note
that, apart from the private member functions, several private data members
are defined as well. Let's have a closer look at the implementation of the
class <code>Scanner</code>:
    <ul>
    <li> First, we have a look at the class's initial section, showing the
conditional inclusion of <code>FlexLexer.h</code>, its <code>class</code> opening, and its
private data. Its <code>public</code> section starts off by defining the <code>enum Error</code>
defining various symbolic constants for errors that may be detected:
                <pre>
#if ! defined(_SKIP_YYFLEXLEXER_)
#include &lt;FlexLexer.h&gt;
#endif

class Scanner: public yyFlexLexer
{
    std::stack&lt;yy_buffer_state *&gt;   d_state;
    std::vector&lt;std::string&gt;        d_fileName;
    std::string                     d_nextSource;

    static size_t const           s_maxDepth = 10;

    public:
        enum Error
        {
            invalidInclude,
            circularInclusion,
            nestingTooDeep,
            cantRead,
        };
</pre>
<p>
<li> As they are objects, the class's data members are initialized
automatically by <code>Scanner</code>'s <a name="an3090"></a>
constructor. It activates the initial input
(and output) file and pushes the name of the initial input file. Here is its
implementation:
        <pre>
    #include "scanner.ih"

    Scanner::Scanner(istream *yyin, string const &amp;initialName)
    {
        switch_streams(yyin, yyout);
        d_fileName.push_back(initialName);
    }
</pre>
    <li> The scanning process proceeds as follows:
    once the scanner extracts a filename from an <code>#include</code> directive, a
switch to another file is performed by <code>pushSource()</code>.  If the filename
could not be extracted, the scanner throws an <code>invalidInclude</code> <a name="an3091"></a>
exception
value. The <code>pushSource()</code> member and the matching function <code>popSource()</code>
handle  file switching. Switching to another file proceeds as follows:
        <ul>
        <li> First, the current depth of the <code>include</code>-nesting is inspected.
If <code>s_maxDepth</code> is reached, the stack is considered full, and the scanner
throws a <code>nestingTooDeep</code> exception.
        <li> Next, <code>throwOnCircularInclusion()</code> is called to avoid circular
inclusions when switching to new files. This function throws an exception if a
filename is included twice, using a simple literal name check. Here is its
implementation:
        <pre>
    #include "scanner.ih"

    void Scanner::throwOnCircularInclusion()
    {
        vector&lt;string&gt;::iterator
            it = find(d_fileName.begin(), d_fileName.end(), d_nextSource);

        if (it != d_fileName.end())
            throw circularInclusion;
    }
</pre>
        <li> Then a new <code>ifstream</code> object is created, for the filename
in <code>nextSource</code>. If this fails, the scanner throws a <code>cantRead</code> exception.
        <li> Finally, a new <a name="an3092"></a>
<code>yy_buffer_state</code> is created for the newly
opened stream, and the lexical scanner is instructed to switch to that stream
using <code>yyFlexLexer</code>'s member function <a name="an3093"></a>
<code>yy_switch_to_buffer()</code>.
    </ul>
    Here is <code>pushSource()</code>'s implementation:
        <pre>
    #include "scanner.ih"

    void Scanner::pushSource(yy_buffer_state *current, size_t size)
    {
        if (d_state.size() == s_maxDepth)
            throw nestingTooDeep;

        throwOnCircularInclusion();
        d_fileName.push_back(d_nextSource);

        ifstream *newStream = new ifstream(d_nextSource.c_str());

        if (!*newStream)
            throw cantRead;

        d_state.push(current);
        yy_switch_to_buffer(yy_create_buffer(newStream, size));
    }
</pre>
    <li> The class <code>yyFlexLexer</code> provides a series of member functions that
can be used to switch files. The file-switching capability of a
<code>yyFlexLexer</code> object is founded on the <code>struct yy_buffer_state</code>,
containing the state of the <a name="an3094"></a>
<em>scan-buffer</em> of the currently read file.  This
buffer is pushed on the <code>d_state</code> stack when an <code>#include</code> is
encountered. Then <code>yy_buffer_state</code>'s contents are replaced by the buffer
created for the file to be processed next. Note that in the <code>flex</code>
specification file the function <code>pushSource()</code> is called as
        <pre>
        pushSource(YY_CURRENT_BUFFER, YY_BUF_SIZE);
</pre>
    <a name="an3095"></a>
<code>YY_CURRENT_BUFFER</code> and <a name="an3096"></a>
<code>YY_BUF_SIZE</code> are macros that are <em>only</em>
available in the rules section of the lexer specification file, so they must
be passed as arguments to <code>pushSource()</code>.  Currently it is <em>not</em> possible
to use these macros in the <code>Scanner</code> class's member functions directly.
    <li> Note that <a name="an3097"></a>
<code>yylineno</code> is not updated when a <a name="an3098"></a>
file switch is
performed. If line numbers are to be monitored, then the current value of
<code>yylineno</code> should be pushed on a stack, and <code>yylineno</code> should be reset by
<code>pushSource()</code>, whereas <code>popSource()</code> should reinstate a former value of
<code>yylineno</code> by popping a previously pushed value from the
stack. <code>Scanner</code>'s current implementation maintains a simple <a name="an3099"></a>
stack of
    <a name="an3100"></a>
<code>yy_buffer_state</code> pointers. Changing that into a stack of
<code>pair&lt;yy_buffer_state *, size_t&gt;</code> elements would allow us to save (and
restore) line numbers as well. This modification is left as an <a name="an3101"></a>
exercise to
the reader.
    <li> The member function <code>popSource()</code> is called to pop the previously
pushed buffer from the stack, allowing the scanner to continue its scan just
beyond the just processed <code>#include</code> directive. The member <code>popSource()</code>
first inspects the size of the <code>d_state</code> stack: if empty, <code>false</code> is
returned and the function terminates. If not empty, then the current buffer is
deleted, to be replaced by the state waiting on top of the stack. The file
switch is performed by the <code>yyFlexLexer</code> members <a name="an3102"></a>
<code>yy_delete_buffer()</code> and
<code>yy_switch_to_buffer()</code>. Note that <code>yy_delete_buffer()</code> takes care of the
closing of the <code>ifstream</code> and of deleting the memory allocated for this
stream in <code>pushSource()</code>. Furthermore, the filename that was last entered in
the <code>d_fileName</code> vector is removed. Having done all this, the function
returns <code>true</code>:
        <pre>
    #include "scanner.ih"

    bool Scanner::popSource(yy_buffer_state *current)
    {
        if (d_state.empty())
            return false;

        yy_delete_buffer(current);
        yy_switch_to_buffer(d_state.top());
        d_state.pop();
        d_fileName.pop_back();

        return true;
    }
</pre>
    <li> Two service members are offered: <code>stackTrace()</code> dumps the names of
the currently pushed files to the standard error stream. It may be called by
exception catchers. Here is its implementation:
        <pre>
    #include "scanner.ih"

    void Scanner::stackTrace()
    {
        for (size_t idx = 0; idx &lt; d_fileName.size() - 1; ++idx)
            cerr &lt;&lt; idx &lt;&lt; ": " &lt;&lt; d_fileName[idx]  &lt;&lt; " included " &lt;&lt;
                                    d_fileName[idx + 1]  &lt;&lt; endl;
    }
</pre>
    <li> <code>lastFile()</code> returns the name of the currently processed file. It
may be implemented inline:
                <pre>
inline std::string const &amp;Scanner::lastFile()
{
    return d_fileName.back();
}
</pre>
<p>
<li> The lexical scanner itself is defined in <code>Scanner::yylex()</code>.
Therefore, <code>int yylex()</code> must be declared by the class <code>Scanner</code>, as it
overrides <code>FlexLexer</code>'s virtual member <code>yylex()</code>.
    </ul>
<p>
<a name="l393"></a>
<strong>20.8.1.3: Using a `Scanner' object</strong>
        <a name="concrete/scanmain"></a>    The program using our <code>Scanner</code> is very simple. It expects a filename
indicating where to start the scanning process. Initially the number of
arguments is checked. If at least one argument was given, then an <code>ifstream</code>
object is created. If this object can be created, then a <code>Scanner</code> object is
constructed, receiving the address of the <code>ifstream</code> object and the name of
the initial input file as its arguments. Then the <code>Scanner</code> object's
<code>yylex()</code> member is called. The scanner object throws <code>Scanner::Error</code>
exceptions if it fails to perform its tasks properly. These exceptions are
caught near <code>main()</code>'s end. Here is the program's source:
        <pre>
    #include "lexer.h"
    using namespace std;

    int main(int argc, char **argv)
    {
        if (argc == 1)
        {
            cerr &lt;&lt; "Filename argument required\n";
            exit (1);
        }
        ifstream yyin(argv[1]);
        if (!yyin)
        {
            cerr &lt;&lt; "Can't read " &lt;&lt; argv[1] &lt;&lt; endl;
            exit(1);
        }
        Scanner scanner(&amp;yyin, argv[1]);
        try
        {
            return scanner.yylex();
        }
        catch (Scanner::Error err)
        {
            char const *msg[] =
            {
                "Include specification",
                "Circular Include",
                "Nesting",
                "Read",
            };
            cerr &lt;&lt; msg[err] &lt;&lt; " error in " &lt;&lt; scanner.lastFile() &lt;&lt;
                                ", line " &lt;&lt; scanner.lineno() &lt;&lt; endl;
            scanner.stackTrace();
            return 1;
        }
        return 0;
    }
</pre>
<p>
<a name="l394"></a>
<strong>20.8.1.4: Building the program</strong>
        <a name="concrete/scancompile"></a>    The final program is constructed in two steps. These steps are given for a
<a name="an3103"></a>
Unix system, on which <a name="an3104"></a>
<code>flex</code> and the <a name="an3105"></a>
Gnu <strong>C++</strong> compiler <a name="an3106"></a>
<code>g++</code> have
been installed:
    <ul>
    <li> First, the lexical scanner's source is created using <code>flex</code>. For
this the following command can be given:
        <pre>
    flex lexer
</pre>
    <li> Next, all sources are compiled and linked. In situations where the
default <code>yywrap()</code> function is used, the <a name="an3107"></a>
<code>libfl.a</code> library should be
linked against the final program. Normally, that's not required, and the
program can be constructed as, e.g.:
        <pre>
    g++ -o lexer *.cc
</pre>
     </ul>
    For the purpose of <a name="an3108"></a>
debugging a lexical scanner, the matched rules
and the returned tokens provide useful information. When
the <a name="an3109"></a>
<code>%option debug</code> was specified, debugging code will be included in the
generated scanner. To obtain debugging info, this code must also be
activated. Assuming the scanner object is called <code>scanner</code>, the statement
    <a name="an3110"></a>

        <pre>
        scanner.set_debug(true);
</pre>
    will produce debugging info to the standard error stream.
<p>
<a name="BISONFLEX"></a><a name="l395"></a>
<h3>20.8.2: Using both `bisonc++' and `flex'</h3>
    <a name="concrete/usingbison"></a>When an <a name="an3111"></a>
input language exceeds a certain level of complexity, a <a name="an3112"></a>
<em>parser</em>
is often used to control the complexity of the input language. In this case, a
<a name="an3113"></a>
<em>parser generator</em> can be used to generate the code verifying the input's
<a name="an3114"></a>
grammatical correctness.  The <a name="an3115"></a>
lexical scanner (preferably composed into
the parser) provides chunks of the input, called <a name="an3116"></a>
<em>tokens</em>. The parser then
processes the series of tokens generated by its lexical scanner.
<p>
Starting point when developing programs that use both parsers and scanners is
the <a name="an3117"></a>
grammar. The grammar defines a <em>set of tokens</em> which can be returned
by the lexical scanner (commonly called the <a name="an3118"></a>
<em>lexer</em>).
<p>
Finally, auxiliary code is provided to `fill in the blanks': the <a name="an3119"></a>
actions
performed by the parser and by the lexer are not normally specified literally
in the <a name="an3120"></a>
grammatical rules or lexical <a name="an3121"></a>
regular expressions, but should be
implemented in <em>member functions</em>, called from within the parser's
rules or which are associated with the lexer's regular expressions.
<p>
In the previous section we've seen an example of a <strong>C++</strong> class generated by
<a name="an3122"></a>
<code>flex</code>. In the current section we concentrate on the parser. The
parser can be generated from a grammar specification, processed by the
program <a name="an3123"></a>
<code>bisonc++</code>. The grammar specification required for <code>bisonc++</code> is
similar to the specifications required for <a name="an3124"></a>
<code>bison</code> (and an existing program
<a name="an3125"></a>
<code>bison++</code>, written in the early nineties by the Frenchman
    <a name="an3126"></a>
 <em>Alain Coetmeur</em>), but <code>bisonc++</code> generates a
<strong>C++</strong> which more closely follows present-day standards than <code>bison++</code>,
which still shows many <strong>C</strong>-like features.
<p>
In this section a program is developed converting
    <a name="an3127"></a>
<em>infix expressions</em>, in which binary operators are written between
their operands, to <a name="an3128"></a>
<em>postfix expressions</em>, in which binary operators are
written behind their operands. Furthermore, the unary operator <code>-</code> will be
converted from its prefix notation to a postfix form.  The unary <code>+</code>
operator is ignored as it requires no further actions. In essence our little
calculator is a micro compiler, transforming numerical expressions into
assembly-like instructions.
<p>
Our <a name="an3129"></a>
calculator will recognize a very basic set of operators:
<a name="an3130"></a>
multiplication, <a name="an3131"></a>
addition, <a name="an3132"></a>
parentheses, and the unary minus. We'll
distinguish <a name="an3133"></a>
real numbers from integers, to illustrate a subtlety in
bison-like grammar specifications. That's all. The purpose of this section is,
after all, to illustrate the construction of a <strong>C++</strong> program that uses both
a parser and a lexical scanner, rather than to construct a full-fledged
calculator.
<p>
In the coming sections we'll develop the grammar specification for
<code>bisonc++</code>. Then, the regular expressions for the scanner are specified
according to <code>flex</code>' requirements. Finally the program is constructed.
<p>
<a name="l396"></a>
<strong>20.8.2.1: The `bisonc++' specification file</strong>
        <a name="concrete/bison"></a>The <a name="an3134"></a>
grammar specification file required by <a name="an3135"></a>
<code>bisonc++</code> is comparable to
the specification file required by <a name="an3136"></a>
<code>bison</code>. Differences are related to the
class nature of the resulting parser. Our calculator will distinguish real
numbers from integers, and will support a basic set of arithmetic operators.
<p>
<code>Bisonc++</code> should be used as follows:
    <ul>
    <li> As usual, a grammar must be defined. With <code>bisonc++</code> this is no
        different, and <code>bisonc++</code> grammar definitions are for all practical
        purposes identical to <code>bison</code>'s grammar definitions.
    <li> Having specified the grammar and (usually) some declarations
        <code>bisonc++</code> is able to generate files defining the parser class and
        the implementation of the member function <code>parse()</code>.
    <li> All class members (except those that are required for the proper
        functioning of the member <code>parse()</code>) must be
        implemented by the programmer.  Of course, they should also be
        declared in the parser class's header.  At the very least the member
        <a name="an3137"></a>
<code>lex()</code> must be implemented. This member is called by <code>parse()</code> to
        obtain the next available token.  However, <code>bisonc++</code> offers a
        facility providing a standard implementation of the function
        <strong>lex()</strong>. The member function
            <a name="an3138"></a>
<code>error(char const *msg)</code>
       is given a simple default implementation which may be modified by the
        programmer. The member function <code>error()</code> is called when <code>parse()</code>
        detects (syntactical) errors.
    <li> The parser can now be used in a program. A very simple example would
        be:
        <pre>
    int main()
    {
        Parser parser;
        return parser.parse();
    }
</pre>
    </ul>
<p>
The <code>bisonc++</code> specification file consists of two sections:
    <ul>
    <li> The <a name="an3139"></a>
 <a name="an3140"></a>
<em>declaration section</em>. In
        this section bison's tokens, and the <a name="an3141"></a>
priority rules for the
        operators are declared. However, <code>bisonc++</code> also supports several
        new declarations.  These new declarations are important and are
        discussed below.
    <li> The <a name="an3142"></a>
 <em>rules section</em>. The
       <a name="an3143"></a>
grammatical rules define the grammar. This section is identical to
        the one required by <code>bison</code>, albeit that some members that were
        available in <code>bison</code> and <code>bison++</code> are considered obsolete in
        <code>bisonc++</code>, while other members can now be used in a wider context.
        For example, <strong>ACCEPT()</strong> and <strong>ABORT()</strong> can be called from any
        member called from the parser's action blocks to terminate the parsing
        process.
    </ul>
Readers familiar with <code>bison</code> should note that there is no
    <a name="an3144"></a>
<em>header section</em> anymore. Header sections are used by bison to provide
for the necessary declarations allowing the compiler to compile the <strong>C</strong>
function generated by <code>bison</code>. In <strong>C++</strong> declarations are part of or
already used by class definitions. Therefore, a parser generator generating a
<strong>C++</strong> class and some of its member functions does not require a header
section anymore.
<p>
<a name="BISONDEF"></a><p><strong>The declaration section</strong><br>
            <a name="concrete/definition"></a>    The <a name="an3145"></a>
declaration section contains several declarations, among which all
tokens used in the grammar and the <a name="an3146"></a>
priority rules of the mathematical
operators. Moreover, several new and important specifications can be used
here. Those that are relevant to our current example and only available in
<code>bisonc++</code> are discussed here. The reader is referred to <code>bisonc++</code>'s
<em>man-page</em> <a name="an3147"></a>
 for a full description.
    <ul>
    <li> <a name="an3148"></a>
<strong>%baseclass-header</strong> <code>header</code> <br>
          Defines the pathname of the file to contain (or containing) the
           parser's base class. Defaults to the name of the parser class plus
           the suffix <code>base.h</code>.
    <li> <a name="an3149"></a>
<strong>%baseclass-preinclude</strong> <code>header</code><br>
          Use <code>header</code> as the pathname to the file pre-included in the
           parser's base-class header.  This declaration is useful in
           situations where the base class header file refers to types which
           might not yet be known. E.g., with <strong>%union</strong> a <strong>std::string *</strong>
           field might be used. Since the class <strong>std::string</strong> might not yet
           be known to the compiler once it processes the base class header
           file we need a way to inform the compiler about these classes and
           types. The suggested procedure is to use a pre-include header file
           declaring the required types. By default <code>header</code> will be
           surrounded by double quotes (using, e.g., <code>#include "header"</code>).
           When the argument is surrounded by angle brackets <code>#include
           &lt;header&gt;</code> will be included. In the latter case, quotes might be
           required to escape interpretation by the shell (e.g., using <code>-H
           '&lt;header&gt;'</code>).
    <li> <a name="an3150"></a>
<strong>%class-header</strong> <code>header</code> <br>
          Defines the pathname of the file to contain (or containing) the
           parser class. Defaults to the name of the parser class plus the
           suffix <code>.h</code>
    <li> <a name="an3151"></a>
<strong>%class-name</strong> <code>parser-class-name</code> <br>
          Declares the class name of this parser. This declaration replaces
           the <strong>%name</strong> declaration previously used by <code>bison++</code>. It
           defines the name of the <strong>C++</strong> class that will be
           generated. Contrary to <code>bison++</code>'s <strong>%name</strong> declaration,
           <strong>%class-name</strong> may appear anywhere in the first section of the
           grammar specification file. It may be defined only once. If no
           <strong>%class-name</strong> is specified the default class name <code>Parser</code> will
           be used.
    <li> <strong>%debug</strong> <br>
           Provide <strong>parse()</strong> and its support functions with debugging code,
            showing the actual parsing process on the standard output
            stream. When included, the debugging output is active by default,
            but its activity may be controlled using the <strong>setDebug(bool
            on-off)</strong> member. Note that no <code>#ifdef DEBUG</code> macros are used
            anymore. By rerunning <code>bisonc++</code> without the <strong>--debug</strong> option
            an equivalent parser is generated not containing the debugging
            code.
    <li> <a name="an3152"></a>
<strong>%filenames</strong> <code>header</code> <br>
           Defines the generic name of all generated files, unless overridden
            by specific names. By default the generated files use the
           class-name as the generic file name.
    <li> <a name="an3153"></a>
<strong>%implementation-header</strong> <code>header</code> <br>
          Defines the pathname of the file to contain (or containing) the
           implementation header. Defaults to the name of the generated parser
           class plus the suffix <code>.ih</code>. The implementation header should
           contain all directives and declarations <em>only</em> used by the
           implementations of the parser's member functions. It is the only
           header file that is included by the source file containing
           <code>parse()</code>'s implementation. It is suggested that user defined
           implementations of other class members use the same convention,
           thus concentrating all directives and declarations that are
           required for the compilation of other source files belonging to the
           parser class in one header file.
    <li> <a name="an3154"></a>
<strong>%parsefun-source</strong> <code>source</code> <br>
           Defines the pathname of the file containing the parser member
            <strong>parse()</strong>. Defaults to <code>parse.cc</code>.
    <li> <strong>%scanner</strong> <code>header</code><br>
           Use <code>header</code> as the pathname to the file pre-included in the
            parser's class header. This file should define a class
            <strong>Scanner</strong>, offering a member <code>int yylex()</code> producing the next
            token from the input stream to be analyzed by the parser generated
            by <code>bisonc++</code>. When this option is used the parser's member
            <code>int lex()</code> will be predefined as (assuming the parser class
            name is <code>Parser</code>):
                <pre>
    inline int Parser::lex()
    {
        return d_scanner.yylex();
    }
</pre>
           and an object <code>Scanner d_scanner</code> will be composed into the
            parser. The <code>d_scanner</code> object will be constructed using its
            default constructor. If another constructor is required, the
            parser class may be provided with an appropriate (overloaded)
            parser constructor after having constructed the default parser
            class header file using <code>bisonc++</code>.  By default <code>header</code> will
            be surrounded by double quotes (using, e.g., <code>#include
            "header"</code>).  When the argument is surrounded by angle brackets
            <code>#include &lt;header&gt;</code> will be included.
    <li> <a name="an3155"></a>
<strong>%stype typename</strong> <br>
           The type of the semantic value of tokens.  The specification
            <code>typename</code> should be the name of an unstructured type (e.g.,
            <code>size_t</code>). By default it is <code>int</code>. See <strong>YYSTYPE</strong> in
            <code>bison</code>.  It should not be used if a <strong>%union</strong> specification is
            used.  Within the parser class, this type may be used as
            <code>STYPE</code>.
    <li> <a name="an3156"></a>
<strong>%union</strong> <code>union-definition</code> <br>
           Acts identically to the <code>bison</code> declaration.  As with <code>bison</code>
            this generates a union for the parser's semantic type.  The union
            type is named <code>STYPE</code>. If no <strong>%union</strong> is declared, a simple
            stack-type may be defined using the <strong>%stype</strong> declaration. If no
            <strong>%stype</strong> declaration is used, the default stacktype (<code>int</code>) is
            used.
    </ul>
    An example of a <code>%union</code> declaration is:
        <pre>
    %union
    {
        int     i;
        double  d;
    };
</pre>
    A union <a name="an3157"></a>
 cannot contain objects as its fields,
as <a name="an3158"></a>
 <a name="an3159"></a>
 constructors
cannot be called when a union is created. This means that
    <a name="an3160"></a>
 a <code>string</code> cannot be a member of the
union. A <code>string *</code>, however, <em>is</em> a possible union member. By the way:
the <a name="an3161"></a>
lexical scanner does not have to know about such a union. The scanner
can simply pass its scanned text to the parser through its <a name="an3162"></a>
<code>YYText()</code>
<a name="an3163"></a>
 member function. For example, using
a statement like
        <pre>
    $$.i = A2x(scanner.YYText());
</pre>
    <a name="an3164"></a>
matched text may be converted to a value of an appropriate type.
<p>
Tokens and non-terminals can be associated with union fields. This is
strongly advised, as it prevents type mismatches, since the compiler will be
able to check for type correctness. At the same time, the bison specific
variabels <code>$$</code>, <code>$1</code>, <code>$2</code>, etc. may be used, rather than the full field
specification (like <code>$$.i</code>).  A non-terminal or a token may be associated
with a union field using the
        <a name="an3165"></a>

        <a name="an3166"></a>

        <a name="an3167"></a>

    <code>&lt;fieldname&gt;</code> specification. E.g.,
        <pre>
    %token &lt;i&gt; INT          // token association (deprecated, see below)
           &lt;d&gt; DOUBLE
    %type  &lt;i&gt; intExpr      // non-terminal association
</pre>
    In the example developed here, note that both the tokens and the
non-terminals can be associated with a field of the union. However, as noted
before, the lexical scanner does not have to know about all this. In our
opinion, it is cleaner to let the scanner do just one thing: scan texts. The
<em>parser</em>, knowing what the input is all about, may then convert strings like
<code>"123"</code> to an integer value. Consequently, the association of a union field
and a token is discouraged.
        <a name="an3168"></a>

    In the upcoming description of the rules of the grammar this will be
illustrated further.
<p>
In the <code>%union</code> discussion the
        <a name="an3169"></a>

        <a name="an3170"></a>

    <code>%token</code> and <code>%type</code> specifications should be noted. They are used to
specify the tokens (<a name="an3171"></a>
terminal symbols) that can be returned by
the lexical scanner, and to specify the return types of
non-terminals.  Apart from <code>%token</code> the <a name="an3172"></a>
token indicators
        <a name="an3173"></a>
 <code>%left</code>,
        <a name="an3174"></a>
 <code>%right</code> and
        <a name="an3175"></a>
 <code>%nonassoc</code>
        <a name="an3176"></a>

    may be used to specify the <a name="an3177"></a>
associativity of operators. The tokens
mentioned at these indicators are interpreted as tokens indicating operators,
associating in the indicated direction. The <a name="an3178"></a>
precedence of operators
        <a name="an3179"></a>
<a name="an3180"></a>
<a name="an3181"></a>

 is given by their order: the first specification has the lowest priority. To
overrule a certain precedence in a certain context, <a name="an3182"></a>

<code>%prec</code> can be used. As all this is standard <code>bisonc++</code> practice, it isn't
further elaborated here. The documentation provided with <code>bisonc++</code>'s
distribution should be consulted for further reference.
<p>
Here is the specification of the calculator's declaration section:
                <pre>
%filenames parser
%scanner ../scanner/scanner.h
%lines

%union {
    int i;
    double d;
};

%token  INT
        DOUBLE

%type   &lt;i&gt; intExpr
%type   &lt;d&gt; doubleExpr

%left   '+'
%left   '*'
%right  UnaryMinus
</pre>
<p>
In the declaration section <code>%type</code> specifiers are used, associating the
<code>intExpr</code> rule's value (see the next section) to the <code>i</code>-field of the
semantic-value union, and associating <code>doubleExpr</code>'s value to the
<code>d</code>-field. At first sight this may look complex, since the expression rules
must be included for each individual return type. On the other hand, if the
union itself would have been used, we would still have had to specify
somewhere in the returned semantic values what field to use: less rules, but
more complex and error-prone code.
<p>
<p><strong>The grammar rules</strong><br>
            <a name="concrete/rules"></a>    The rules and actions of the grammar are specified as usual. The grammar
for our little calculator is given below. There are quite a few rules, but
they illustrate various features offered by <code>bisonc++</code>. In particular, note
that no action block requires more than a single line of code. This keeps the
organization of the grammar relatively simple, and therefore enhances its
readability and understandability. Even the rule defining the parser's proper
termination (the empty line in the <code>line</code> rule) uses a single member
function call <code>done()</code>. The implementation of that function is simple, but
interesting in that it calls <strong>Parser::ACCEPT()</strong>, showing that the
<strong>ACCEPT()</strong> member can be called indirectly from a production rule's action
block. Here are the grammar's production rules:
                <pre>
    lines:
        lines
        line
    |
        line
    ;

    line:
        intExpr
        '\n'
        {
            display($1);
        }
    |
        doubleExpr
        '\n'
        {
            display($1);
        }
    |
        '\n'
        {
            done();
        }
    |
        error
        '\n'
        {
            reset();
        }
    ;

    intExpr:
        intExpr '*' intExpr
        {
            $$ = exec('*', $1, $3);
        }
    |
        intExpr '+' intExpr
        {
            $$ = exec('+', $1, $3);
        }
    |
        '(' intExpr ')'
        {

            $$ = $2;
        }
    |
        '-' intExpr         %prec UnaryMinus
        {
            $$ = neg($2);
        }
    |
        INT
        {
            $$ = convert&lt;int&gt;();
        }
    ;

    doubleExpr:
        doubleExpr '*' doubleExpr
        {
            $$ = exec('*', $1, $3);
        }
    |
        doubleExpr '*' intExpr
        {
            $$ = exec('*', $1, d($3));
        }
    |
        intExpr '*' doubleExpr
        {
            $$ = exec('*', d($1), $3);
        }
    |
        doubleExpr '+' doubleExpr
        {
            $$ = exec('+', $1, $3);
        }
    |
        doubleExpr '+' intExpr
        {
            $$ = exec('+', $1, d($3));
        }
    |
        intExpr '+' doubleExpr
        {
            $$ = exec('+', d($1), $3);
        }
    |
        '(' doubleExpr ')'
        {
            $$ = $2;
        }
    |
        '-' doubleExpr         %prec UnaryMinus
        {

            $$ = neg($2);
        }
    |
        DOUBLE
        {
            $$ = convert&lt;double&gt;();
        }
    ;
</pre>
<p>
The above grammar is used to implement a simple <a name="an3183"></a>
calculator in which
integer and real values can be negated, added, and multiplied, and in which
standard priority rules can be circumvented using parentheses. The grammar
shows the use of typed nonterminal symbols: <code>doubleExpr</code> is linked to real
(double) values, <code>intExpr</code> is linked to integer values. Precedence and type
association is defined in the parser's definition section.
<p>
<p><strong>The Parser's header file</strong><br>
            <a name="concrete/parserh"></a>Various functions called from the grammar are defined as template
functions. <code>Bisonc++</code> generates various files, among which the file defining
the parser's class. Functions called from the production rule's action blocks
are usually member functions of the parser, and these member functions must be
declared and defined. Once <code>bisonc++</code> has generated the header file defining
the parser's class it will not automatically rewrite that file, allowing the
programmer to add new members to the parser class. Here is the <code>parser.h</code>
file as used for our little calculator:
        <pre>
#ifndef Parser_h_included
#define Parser_h_included

#include &lt;iostream&gt;
#include &lt;sstream&gt;
#include &lt;bobcat/a2x&gt;

#include "parserbase.h"
#include "../scanner/scanner.h"


#undef Parser
class Parser: public ParserBase
{
    std::ostringstream d_rpn;
    // $insert scannerobject
    Scanner d_scanner;

    public:
        int parse();

    private:
        template &lt;typename Type&gt;
            Type exec(char c, Type left, Type right);
        template &lt;typename Type&gt;
            Type neg(Type op);
        template &lt;typename Type&gt;
            Type convert();

        void display(int x);
        void display(double x);
        void done() const;
        void reset();
        void error(char const *msg);
        int lex();
        void print();

        static double d(int i);

    // support functions for parse():

        void executeAction(int d_production);
        void errorRecovery();
        int lookup();
        void nextToken();
};


inline double Parser::d(int i)
{
    return i;
}

template &lt;typename Type&gt;
Type Parser::exec(char c, Type left, Type right)
{
    d_rpn &lt;&lt; " " &lt;&lt; c &lt;&lt; " ";
    return c == '*' ? left * right : left + right;
}

template &lt;typename Type&gt;
Type Parser::neg(Type op)
{
    d_rpn &lt;&lt; " n ";
    return -op;
}

template &lt;typename Type&gt;
Type Parser::convert()
{
    Type ret = FBB::A2x(d_scanner.YYText());
    d_rpn &lt;&lt; " " &lt;&lt; ret &lt;&lt; " ";
    return ret;
}

inline void Parser::error(char const *msg)
{
    std::cerr &lt;&lt; msg &lt;&lt; std::endl;
}

inline int Parser::lex()
{
    return d_scanner.yylex();
}

inline void Parser::print()
{}

#endif
</pre>
<p>
<a name="l397"></a>
<strong>20.8.2.2: The `flex' specification file</strong>
        <a name="concrete/bisonflexspec"></a>    The flex-specification file used by our calculator is
simple: blanks are skipped, single characters are returned, and
numerical values are returned as either <code>Parser::INT</code> or
<code>Parser::DOUBLE</code> tokens. Here is the complete <code>flex</code>
specification file:
        <pre>
%{
    #define _SKIP_YYFLEXLEXER_
    #include "scanner.ih"

    #include "../parser/parserbase.h"
%}

%option yyclass="Scanner" outfile="yylex.cc" c++ 8bit warn noyywrap
%option debug

%%

[ \t]                       ;
[0-9]+                      return Parser::INT;

"."[0-9]*                   |
[0-9]+("."[0-9]*)?          return Parser::DOUBLE;

.|\n                        return *yytext;

%%
</pre>
<p>
<a name="l398"></a>
<strong>20.8.2.3: Generating code</strong>
        <a name="concrete/codegeneration"></a>The code <a name="an3184"></a>
 <a name="an3185"></a>
 is generated in the
same way as with <code>bison</code> and <code>flex</code>. In order to have <code>bisonc++</code>
generate the files <code>parser.cc</code> and <code>parser.h</code>, issue the command:
        <pre>
    bisonc++ -V grammar
</pre>
    The option <code>-V</code> will generate the file <code>parser.output</code> showing
information about the internal structure of the provided grammar, among which
its states. It is useful for debugging purposes, and can be left out of the
command if no debugging is required. <code>Bisonc++</code> may detect conflicts
    (<a name="an3186"></a>
shift-reduce conflicts and/or <a name="an3187"></a>
reduce-reduce conflicts) in the
provided grammar. These conflicts may be resolved explicitly, using
<a name="an3188"></a>
disambiguation rules or they are `resolved' by default. A
shift-reduce conflict is resolved by shifting, i.e., the next token is
consumed. A reduce-reduce conflict is resolved by using the first of two
competing production rules. <code>Bisonc++</code> uses identical
    <a name="an3189"></a>
conflict resolution procedures as <code>bison</code> and <code>bison++</code>.
<p>
Once a parser class and parsing member function has been constructed
<a name="an3190"></a>
<code>flex</code> may be used to create a lexical scanner (in, e.g., the file
<code>yylex.cc</code>) using the command
        <pre>
    flex -I lexer
</pre>
<p>
On <a name="an3191"></a>
Unix systems, linking and compiling the generated sources and the
source for the main program (given below) is then realized by a command
comparable to:
        <pre>
    g++ -o calc -Wall *.cc -s
</pre>
    Finally, here is a source file in which the <code>main()</code> function and the
parser object is defined. The parser features the lexical scanner as one of
its data members:
        <pre>
#include "parser/parser.h"

using namespace std;

int main()
{
    Parser parser;

    cout &lt;&lt; "Enter (nested) expressions containing ints, doubles, *, + and "
            "unary -\n"
            "operators. Enter an empty line to stop.\n";

    return parser.parse();
}
</pre>
<p>
<code>Bisonc++</code> can be downloaded from
    <a name="an3192"></a>

    <a target=_top href="http://bisoncpp.sourceforge.net/">http://bisoncpp.sourceforge.net/</a>. It requires the <code>bobcat</code>
library, which can be downloaded from
    <a name="an3193"></a>

    <a target=_top href="http://bobcat.sourceforge.net/">http://bobcat.sourceforge.net/</a>.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus19.html">Previous Chapter</a>
</ul>
<hr>
</body>
</html>
